Skip to content
thesarfo

Note

Generic Views

Using ListCreateAPIView, a concrete class that already combines ListModelMixin and CreateModelMixin, instead of wiring mixins by hand.

views 0

Even though we now know about mixins, we’re not gonna be using them directly in our project. Instead we’re gonna use concrete classes that combine one or more mixins. These classes are called Generic Views.

There is a class called ListCreateApiView that combines two mixins - ListModelMixin and CreateModelMixin. This Generic View contains functionalities for a get and post request method. Now lets say we wanted to use the ListCreateApiView to get or create our products for us, we can do that. see below

First we import the api view from rest framework generics.

from rest_framework.generics import ListCreateAPIView

And then:

class ProductList(ListCreateAPIView):
'''when using this generic view, we need to override the get_queryset and get_serializer_context'''
def get_queryset(self):
return Product.objects.select_related('collection').all()
def get_serializer_class(self):
return ProductSerializer
def get_serializer_context(self):
'''this is the context we pass to the product serializer when creating an instance of the ProductSerializer class'''
return {'request': self.request}

This is much cleaner and concise, but there is a much cleaner way. Now note that we only use the above methods when we have some logic we want to implement before we create a queryset or create a class. Now lets say we just want to return the queryset, since in this scenario we dont have any special logic we want to check. there is a much shorter way to do that

class ProductList(ListCreateAPIView):
queryset = Product.objects.select_related('collection').all()
serializer_class = ProductSerializer
def get_serializer_context(self):
return {'request': self.request}
'''note how we've gotten rid of the two previous methods above'''

Note that this generic view create html forms that can make creating objects very easy.

Similarly, this is how creating and listing collections (post and get requests/methods) can be done with the ListCreateApiView

class CollectionList(ListCreateAPIView):
queryset = Collection.objects.annotate(products_count=Count('products')).all()
serializer_class = CollectionSerializer