Display Multiple Models in One Django Rest Framework View with DjangoRestMultipleModels

Display Multiple Models in One Django Rest Framework View with DjangoRestMultipleModels

Django REST Framework is a powerful package that makes it easy to create REST API's for Django. It comes bundled with everything you need to create a complete API quickly.

There are some edge-cases however, for example when you want to display multiple models in view it becomes tricky and cumbersome. A fix is not far of though.

The package DjangoRestMultipleModels makes it really easy to add multiple models in one view without writing a custom view by your self.

Let's Install DjangoRestMultipleModels

pip install django-rest-multiple-models

Make sure to add ‘drfmultiplemodel’ to your INSTALLED_APPS:



Let's Create Our View with Multiple Models

In this example we are building a hompage where we want to list out two different models to a single view so that it can easily be absorbed by our frontend through one URL endpoint.

You will need to have an ArticleSerializer and a CommentSerializer ready made because we want to display a list of the 5 latest Articles and Comments.


from drf_multiple_model.views import ObjectMultipleModelAPIView

class HomeAPIView(ObjectMultipleModelAPIView):
    permission_classes = (AllowAny,)
    pagination_class = None
    querylist = [
        {'queryset': Article.objects.order_by('-created_at')[:5], 'serializer_class': ArticleSerializer},
        {'queryset': Comment.objects.order_by('-created_at')[:5], 'serializer_class': CommentSerializer},

As you can see we load multiple querysets with in the view with: querylist = [ ]

Make sure to specify not to use pagination pagination_class = None . As DjangoRestMultipleModels does not support the regular way Django Rest Framework does pagination.


NotImplementedError: HomeAPIView cannot use the regular Rest Framework or Django paginators as is. Use one of the included paginators from `drf_multiple_models.pagination or subclass a paginator to add the `format_response` method.

In our use-case we did not need pagination, however, if you really need pagination DjangoRestMultipleModels provides a way to do Limit/OffSet pagination.


from drf_multiple_model.views import ObjectMultipleModelAPIView
from drf_multiple_model.pagination import MultipleModelLimitOffsetPagination

class LimitPagination(MultipleModelLimitOffsetPagination):
    default_limit = 2

class ObjectLimitPaginationView(ObjectMultipleModelAPIView):
    pagination_class = LimitPagination
    querylist = (
        {'queryset': Article.objects.all(), 'serializer_class': ArticleSerializer},
        {'queryset': Comment.objects.all(), 'serializer_class': CommentSerializer},

As you can see for yourself, DjangoRestMultipleModels makes it super simple to combine many models into one big queryset without writing your own view that combines queryset manually.

This tutorial is just scraping the surface of the package and its capabilities, to get a better understanding of the DjangoRestMultipleModels package I encourage you to consolidate the documentation further.

I hope you enjoyed the tutorial and if you have any questions or inputs, just let me know in the comments below.

Freddie Freddie 2 years, 7 months ago 0
Login to Comment
No comments have been posted yet, be the first one to comment.
Query your Django REST API like a GraphQL API with Django RESTQL
Query your Django REST API like a GraphQL API with Django RESTQL
The hype around GraphQL in recent years has been hard to ignore for any web developer. In short, GraphQL is a query language and runtime for APIs, and it has taken the web with storm. GraphQL makes it possible for front-end developers to query data from a single API endpoint and retri...
How to Cache Django REST Framework with Redis
How to Cache Django REST Framework with Redis
Django REST Framework is an awesome package that will aid you in writing REST APIs faster with Django and Python. Though Django REST Framework has many strengths, performance out-of-the-box might not be one of them. However, there are many ways to fix that, and one of them is caching....
How to Rebuild Django-MPTT Tree Structure
How to Rebuild Django-MPTT Tree Structure
Most application utilize some sort of tree structure to managing data, in one form or another. One common use-case is nested categories. If you are using Django for your current project and are in need to implement tree structures, there is a big change you have come across Django-MPT...