Here’s a small tip on how to write some endpoints in Django Rest Framework. DRF
is a very powerful framework for building APIs. It provides the typical actions
(Create, Read, Update, Destroy) for your models. But what if
you want to change the default behavior?
Lets say your API has photo data. Such an endpoint would be implemented in DRF
This is powerful and fast to set up. However returning all the photos in a
service might raise some privacy concerns. How can we return an empty response
at the list endpoint instead?
We can study the source code for the viewset. ModelViewSet#list docs. A safe way to approach
overriding code is to first paste in the original implementation.
verify you haven’t made any regressions.
Then we can decide on how to change
the endpoint. You may decide to require a query param, if no query param is
provided return an empty response.
Here we intercepted the value of queryset and changed the value
based off of the query param.
This works. However we ran into issues later when we wanted to enforce similar
logic on other endpoints. We refactored the endpoint to only
override the get_queryset method:
By the way, to generate the diagram in the header install pylint for python3.
Then run pyreverse -ASmy -o png your_file.py.
If you need help solving your business problems with
software read how to hire me.