I am exposing an API for a particular model, and want to serialize some of its related fields. These related fields are commonly repeated, and I don't want to have to do a numerous db queries for each related field serialization. Is there a simple way to pre-query all related instances, and then have have the RelatedField serializer look it up in a dictionary? Or maybe to specify from the ModelSerializer of the related field?
You can use Django's standard prefetch_related and select_related methods on your queryset.
On the view, use the queryset
attribute, rather than the model
shortcut.
For example...
class ExampleView(generics.ListCreateAPIView):
serializer_class = ExampleSerializer
queryset = Example.objects.select_related(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With