Best way to use serializers and help with django swagger

Hi everyone, I recently started working with Django and DRF to build an API, and although I managed to get everything working, I’m not sure if my approach was the best, or if Django offers a better way of doing these things. So I would like to ask some questions and hear your feedback.

  1. In my project I have some fields that are “create_only” so they are expected to be on the body of a POST call for creation but cannot be modified by PATCH or PUT routes. The way I got this to work was by creating a custom validator and attaching it to the create_only fields, is this a correct approach? Should I create a unique serializer for the PATCH and PUT routes?

One flaw that I noticed with this approach is that when using drf_yasg to generate a swagger documentation the “create_only” fields can be found on the request_body example, if a validator is the correct approach for this use case, should I use the swagger_auto_schema decorator to generate the proper request_body example?

  1. I’m building a simple project where users can create search queries that will collect data from Twitter API. Each search has its ID and the tweets returned by that search and each user can only see the results returned by the searches that they created.

My approach was to create a SeachViewset, with the normal create/list/get/etc routes and I added 1 route that will receive the search ID and get all tweets from that search. Although it works I had some problems with the swagger documentation, since I was using the action decorator with detail=True the documentation expects that the route will return only 1 record instead of many, so I changed detail to False and added pk to the url_path which works but looks unnecessary, so I’m not sure if there’s a better way of doing this. Also, one idea that I had was to create a TwitterView and edit the URL or add a query param to filter by the search ID, I don’t know which approach is the best.

    def query_tweets(self, request, pk=None):
        """list all tweets from a search

        - Requires token authentication.
        - Allows access only to authenticated users.
        queryset = self.filter_queryset(self.get_queryset().filter(search=pk))
        page_data = self.paginate_queryset(queryset)
        serializer = self.get_serializer(instance=page_data, many=True)
        return self.get_paginated_response(