9๐
โ
As of Django REST Framework 2.4, you can now decorate ViewSet
methods with @list_route
to get what you are looking for.
The
@detail_route
decorator containspk
in its URL pattern and is intended for methods which require a single instance. The@list_route
decorator is intended for methods which operate on a list of objects.
These replace the old @link
and @action
decorators which were only able to work as detail routes.
6๐
if you want list of objects then you need list method in your ListApiView:
For example, model is ModelName and serializer class is SerializerClassname
then code will be:
class ExampleView(ListAPIView):
model = ModelNmae
serializer_class = SerializerClassName
permission_classes = (IsAuthenticated,)
def get_queryset(self):
"""
"""
queryset = ModelName.objects.all()
q = self.request.query_params.get('q', None)
if q is not None:
queryset =queryset.filter(name__icontains=q)
return queryset
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
result = [ x.values()[0] for x in serializer.data ]
return Response(result)
๐คArpit Singh
- Nginx location path with proxy_pass
- How to call asynchronous function in Django?
- 413 Payload Too Large on Django server
- Django confirm password validator
- Can i use celery without django
0๐
First, create a viewsets.py
file anywhere in the project and write the following code:
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
class ModelOptsMixin(object):
"""CBV mixin which adds model options to the context."""
def get_context_data(self, **kwargs):
"""Returns the context data to use in this view."""
ctx = super().get_context_data(**kwargs)
if hasattr(self, "model"):
ctx["opts"] = self.model._meta
return ctx
class BaseListView(
LoginRequiredMixin,
PermissionRequiredMixin,
ModelOptsMixin,
HasPermissionsMixin,
ListView,
):
"""ListView CBV with LoginRequiredMixin and PermissionRequiredMixin."""
def base_paginator(self, instance):
"""
Set paginator return context of paginator.
"""
paginator = Paginator(instance, int(settings.DEFAULT_PAGINATION_SIZE))
page = self.request.GET.get("page", 1)
try:
instance_paginator = paginator.page(page)
except PageNotAnInteger:
instance_paginator = paginator.page(1)
except EmptyPage:
instance_paginator = paginator.page(paginator.num_pages)
return instance_paginator
Import BaseListView
and use this.
- Django remote user authentication and security
- Haystack search results: how to use different templates for different models in page.object_list?
Source:stackexchange.com