Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pre-lookup related field models?

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?

like image 996
jacob Avatar asked Apr 24 '13 19:04

jacob


1 Answers

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(...)
like image 175
Tom Christie Avatar answered Oct 14 '22 10:10

Tom Christie