[Django]-Django REST framework – views serving both regular webpages and API responses depending on the request

6πŸ‘

βœ…

I would suggest to keep it separate. With simple CRUD – you will not have the issues with DRY because they are simply different views, consider:

DRF (basically this is all for CRUD, if you want only a list use: ListModelMixin):

class ServiceViewSet(viewsets.ModelViewSet):
    queryset = Service.objects.all()
    serializer_class = ServiceSerializer

I think that merging this into one View – sooner or later will get you into troubles.

What kind of troubles?

  • Your templates can at some point use much more data to display the page to the user than your REST API (simple example: current time) – you will start to implement different context for template and different for REST;
  • and nothing more came to my mind πŸ˜‰ but I have a feeling that two separate views make it much more clean.

I also understand the risk of repeating the same code twice – but you can always extract the repeating code to some helping structures.

As for queryset – if it’s simple – do not bother with one place for storing it. If it can get complicated – again – there’s no problem to store the queryset in some helping structure and use in both views:

class ProjectQuerysets(object):
    my_test_qs = Test.objects.filter(created_at__gte=now-timedelta(seconds=30)).all()

or event something more sophisticated:

class TestQSMixni(object):

    def get_queryset(self, *args, **kwargs):
         return Test.objects.filter(user=self.request.user)  # something like that;

And later:

class TestList(TestQSMixin, APIView):

    def get(self, *args, **kwargs):
        queryset = self.get_queryset()

# and in REST:

class ServiceViewSet(TestQSMixin, viewsets.ModelViewSet):
    serializer_class = ServicesSerializer
    # no queryset needed here

(sorry for example with this services, but I have this in some notes :))

Hope this will help you a little.

At the end – it all depends on your needs πŸ™‚ And the project requirements.

Happy coding.

πŸ‘€opalczynski

Leave a comment