Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Automatically determine `select_related` and `prefetch_related` on ModelSerializer. #1964
I have a serializer that looks the the following:
class ReportSerializer(serializers.ModelSerializer): person = serializers.SlugRelatedField(slug_field='uuid')
which is causing an N +1 select issue because
We likely want to use
It's actually been a conscious design decision to leave the
Attempting to automatically add them would be helpful in many cases, but could also end up failing or giving worse performance in other cases. The other bit that's awkward is that we'd only want to add this to
Of course we'd also have to do the clevernesses of figuring out when to use
Having said all that, might not be averse to building something like this in, in the future. Any thoughts from anyone else?
changed the title from
select_related not being used -> many extra DB queries
Automatically determine `select_related` and `prefetch_related` on ModelSerializer.
Oct 17, 2014
A follow up question, would be "given that DRF does not currently do the
I feel at the very least more documentation is deserved. I was quite
Assuming you're using generic views then specify it on the
And yes, we should make to include some notes on that in the generic view section, plus also have a a section on general usage tips etc. Including:
Okay. That makes sense.
I am curious to hear what others think, but I would love to see some magic
I believe that this approach if implemented correctly can enhance the performance of DRF greatly.
The algorithm for generating the values of the arguments of select_related is:
The algorithm for generating the values of the arguments of prefetch_related is:
The only problem I see here is what happens when the relationship source involves a nested relationship since I don't know how Django performs the queries.
class MySerializer(ModelSerializer): foo = CharField(source='foo.bar.name') class Meta: model = MyModel
Should generate which query exactly?
I think that the query should be:
But I'm not sure what django will do in that case. In any case, I'd use only to ensure only the fields I require are fetched.
I believe that extending this issue to support automatically detecting exactly which fields should be fetched using
We can compromise and specify that we don't support detecting *_related on nested relationships or defer the support for those relationships to later version (which I'd prefer if any of you thinks it's too complex to implement).
At this point in time I'm closing this off in favor of the documentation ticket #1977.
referenced this issue
Nov 6, 2014