In this Tutorial we will learn about the generic view in django rest framework.
Generic API View
This class extends REST Framework's API View class,adding commonly required behaviour for standard lsit and details views.
Attributes of generic view
1.queryset
The queryset that should be used for returning objects from this view.Typically , you must either set this attribute or override get_queryset() method.
2.serializer_class
This serializer class that should be used for validating and deserializing input and for serailizating output.Typically , you must either set this attribute or override the get_serializer_class() method.
3.lookup_field
This model filed that should be used to for performing object lookup of individual model instances. default to "pk"
4.lookup_url_kwargs
lookup_url_kwargs is an attribute in Django REST Framework (DRF) that can be used to customize the keyword arguments used to perform object lookup. Here's an example of how to use it:
#urls.py
urlpatterns = [
path('books/<slug:book_slug>/', BookDetailAPIView.as_view(), name='book-detail'),
]
#views.py
class BookDetailAPIView(generics.RetrieveAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
lookup_field = 'slug'
lookup_url_kwarg = 'book_slug'
# Use 'book_slug' instead of the default 'slug' URL parameter name
def get_object(self):
queryset = self.get_queryset()
filter_kwargs = {self.lookup_field: self.kwargs[self.lookup_url_kwarg]}
obj = generics.get_object_or_404(queryset, **filter_kwargs)
return obj
5.pagination_class
This pagination_class attribute is used for paginating the data. you can used PageNumberPagination,LimitOffsetPagination or CursorPagination.
6.filter_backends
This filter_backends attribute is used for mentioning the which filter backends is implemente in view. example like searchfilter,orderingfiler and many more.
7.pagination_class
This permission_class attribute is use for giving the permission for the particular view. example are IsAuthenticated,IsAdminuser and many more.
method of generic view
1.get_queryset()
This method is used for override the queryset of view.if you want to have some changes in queryset then you can used this method and make changes as per the requirements and return it.
def get_queryset(self):
type = self.request.GET.get("type", None)
is_trek = self.request.GET.get("is_trek", None)
if is_trek:
qs = Expedition.objects.filter(
trek__isnull=False).order_by("-created_at")
else:
qs = Expedition.objects.filter(
type__system=type, trek__isnull=True).order_by("-created_at")
return filtered_qs
2.get_object()
get_object() is a method in Django REST Framework (DRF) that retrieves a single object instance based on the given lookup parameters. Note that if no matching object is found, get_object() will raise a Http404 exception, so it's important to handle this appropriately in your code. Here's an example of how to use it:
#urls.py
urlpatterns = [
path('books/<slug:slug>/', BookDetailAPIView.as_view(), name='book-detail'),
]
#views.py
class BookDetailAPIView(generics.RetrieveAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
lookup_field = 'slug'
def get_object(self):
queryset = self.get_queryset()
obj = queryset.get(slug=self.kwargs['slug'])
return obj
3.get_serializer_class()
get_serializer_class() is a method in Django REST Framework (DRF) that returns the serializer class to be used for a particular view or viewset.This approach allows us to use different serializers for different actions, which can be useful if we need to serialize the data differently for different purposes.Note that the get_serializer_class() method is called every time a serializer is needed, so it's important to keep it lightweight and avoid any unnecessary computations or database queries.
Here's an example of how to use it:
class BookListAPIView(ListAPIView):
queryset = Book.objects.all()
def get_serializer_class(self):
if self.request.query_params.get('detail', False):
return BookDetailSerializer
elif self.action == 'list' or self.action == 'retrieve':
return BookListSerializer
return BookSerializer
4.get_serializer_context()
If you want to sent any context from views.py to serializer class of the view , then you can used this method and send context in the form of key, value form which can easily be retrived in serializer class.
def get_serializer_context(self):
context = super().get_serializer_context()
context.update({"request": self.request,"user":request.user})
return context
5.get_serializer(self,instance=None,data=None,many=False,partial=False)
This method is used to get the serialized data from queryset or model instance. it simply takes the instance or queryset and return serialized data. get_serializer() is a method in Django REST Framework (DRF) that returns an instance of the serializer class that should be used to serialize or deserialize the data for the current request. Here's an example of how to use it:
class BookListAPIView(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
def get_serializer(self, *args, **kwargs):
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
return serializer_class(*args, **kwargs)
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
return Response({"data": serializer.data, "message": "Book List"})
6.get_paginated_response(self,data)
get_pagination_response() is a method in Django REST Framework (DRF) that creates a standardized response for paginated API views. Here's an example of how to use it:
We also override the get_paginated_response() method to return a standardized response for paginated views. We call self.paginator.get_paginated_response(data) to create the response using the paginator attribute set by the pagination_class.
By customizing the get_paginated_response() method, we can provide a standardized response format for paginated API views, including information such as the total number of results, the current page number, and the URL of the next and previous pages.
class BookListAPIView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
pagination_class = MyPaginationClass
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
queryset = self.filter_queryset(self.get_queryset())
# queryset1 = GrandInvoice.objects.filter(invoice_number__icontains=type)
# invoice_list = []
# for q in queryset1:
# invoice_list.append(q.book_uuid)
# qq = Book.objects.filter(uuid__in=invoice_list)
# queryset = queryset.union(qq)
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)
return Response(serializer.data)
def get_paginated_response(self, data):
return self.paginator.get_paginated_response(data)
7.filter_queryset(self,queryset)
If view have used the filter_backends attribute then this method is mendatory beacuse through this method the required search,filter or ordering queryset is filter and the required queryset is return.
Note: If you have used filter_backeds and overide the get_queryset() method then you should pass the queryset into this method before return it in get_queryset() method.
example:
qs=Expedition.objects.filter(type="combo")
filtered_qs = self.filter_queryset(qs)
return filtered_qs
class ExpeditionListAPI(generics.ListAPIView):
queryset = Expedition.objects.all()
serializer_class = AdminExpeditionListSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['title']
def filter_queryset(self, queryset):
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
Concrete View Class
The following classes are the concrete generic views. if you are using the generic views this is normally the level you will be working at unless you need heavily customized behaviour.
The view class can be import from rest_framework.generics
1.ListAPIView 6.ListCreateAPIView
2.CreateAPIView 7.RetriveUpdateAPIView
3.RetriveAPIView 8.RetriveDEstroyAPIView
4.UpdateAPIView 9.RetriveUpdateDestroyAPIView
5.DestroyAPIView
1.ListAPIView
It is used for read_only endpoints to represent a collection of model instances. it provide get method handler.it is extended from ListModelMixin.
from rest_framework.generics import ListAPIView
class EmployeeLists(ListAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
2.CreateAPIView
It is used for create_only endpoints , it provide post method handler.it is extended from CreateModelMixin.
from rest_framework.generics import CreateAPIView
class EmployeeLists(CreateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
3.RetriveAPIView
It is used for read_only endpoints to represent single model instance , it provide get method handler.it is extended from RetriveModelMixin.
# urls.py
urlpatterns = [
path('list/<int:id>/',views.EmployeeLists.as_view()),
]
# views.py
from rest_framework.generics import RetrieveAPIView
class EmployeeLists(RetrieveAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
4.UpdateAPIView
It is used for update_only endpoints to represent single model instance , it provide put and patch method handler.it is extended from UpdateModelMixin.
# urls.py
urlpatterns = [
path('list/<int:id>/',views.EmployeeLists.as_view()),
]
# views.py
from rest_framework.generics import UpdateAPIView
class EmployeeLists(UpdateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
5.DestroyAPIView
It is used for delete_only endpoints to represent single model instance , it provide delete method handler.it is extended from DestroyModelMixin.
# urls.py
urlpatterns = [
path('list/<int:id>/',views.EmployeeLists.as_view()),
]
# views.py
from rest_framework.generics import DestroyAPIView
class EmployeeLists(DestroyAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
6.ListCreateAPIView
It is used for read_write endpoints to represent collection model instance , it get and post delete method handlers. it is extended from ListModelMixin and CreateModelMixin.
# views.py
from rest_framework.generics import ListCreateAPIView
class EmployeeLists(ListCreateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
7.RetriveUpdateAPIView
It is used for read or update endpoints to represent single model instance , it get ,put and patch method handlers. it is extended from RetriveModelMixin and UpdateModelMixin.
# urls.py
urlpatterns = [
path('list/<int:id>/',views.EmployeeLists.as_view()),
]
# views.py
from rest_framework.generics import RetrieveUpdateAPIView
class EmployeeLists(RetrieveUpdateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
8.RetriveDestroyAPIView
It is used for read or delete endpoints to represent single model instance , it get and delete method handlers. it is extended from RetriveModelMixin and DesroyModelMixin.
# urls.py
urlpatterns = [
path('list/<int:id>/',views.EmployeeLists.as_view()),
]
# views.py
from rest_framework.generics import RetrieveDestroyAPIView
class EmployeeLists(RetrieveDestroyAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
9.RetriveUpdateDestroyAPIView
It is used for read , write and delete endpoints to represent single model instance , it get ,put ,patch and delete method handlers. it is extended from RetriveModelMixin,UpdateModelMixin and DesroyModelMixin.
# urls.py
urlpatterns = [
path('list/<int:id>/',views.EmployeeLists.as_view()),
]
# views.py
from rest_framework.generics import RetrieveUpdateDestroyAPIView
class EmployeeLists(RetrieveUpdateDestroyAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
For the simplicity , you can perform CRUD operation just like below.
# urls.py
urlpatterns = [
path('list-create/',views.EmployeeListCreate.as_view()),
path('retrive-update-delete/<int:id>/',views.EmployeeRetriveUpdaeDelete.as_view()),
]
# views.py
from rest_framework.generics import RetrieveUpdateDestroyAPIView,ListCreateAPIView
class EmployeeListCreate(ListCreateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
class EmployeeRetriveUpdaeDelete(RetrieveUpdateDestroyAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
example:
class InventoryGroupListV2APIView(generics.ListAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = InventorygroupListSerializer
pagination_class = InventoryGroupPagination
filter_backends = [filters.SearchFilter]
search_fields = ['name', 'manufactured_by', 'brand',
'manufacture_fk__name', 'brand_fk__name']
def filter_queryset(self, queryset):
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
def get_queryset(self):
queryset = InventoryGroup.objects.filter(company=self.request.user.company).order_by("-created_at")
filtered_qs = self.filter_queryset(queryset)
return filtered_qs
def list(self, request):
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({"message": "Inventory Item List", "data": serializer.data})
serializer = self.get_serializer(queryset, many=True)
return Response({"message": "Inventory Item List", "data": serializer.data})
Amanda Martines 5 days ago
Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.
ReplyBaltej Singh 5 days ago
Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
ReplyMarie Johnson 5 days ago
Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
Reply