You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ListSerializer.to_representation does not respect prefetches #2704
I noticed some undesirable behavior around ListSerializer's implementation of to_representation in the context of relations prefetched with Django 1.7's Prefetch object.
I am talking about this block of code:
# Dealing with nested relationships, data can be a Manager,
# so, first get a queryset from the Manager if needed
iterable = data.all() if isinstance(data, (models.Manager, query.QuerySet)) else data
return [
self.child.to_representation(item) for item in iterable
]
To demonstrate the problem, consider a request made to fetch all auth.Users and their related auth.Groups matching a certain filter. This can be done with Prefetch like so:
Lets look at the first user and his prefetched groups:
>>> user = users_with_test_groups[0]
>>> user.groups.all()
[<Group: test>]
... so far, so good. Now let's add DRF into the mix; I have a UserSerializer and a related GroupSerializer:
UserSerializer(ModelSerializer):
groups = GroupSerializer(many=True)
...
GroupSerializer(ModelSerializer):
...
If I call UserSerializer(users_with_test_groups, many=True).data, I expect to see my first user returned with only those related groups that contain test. But I actually see ALL groups related to that user!
This is because calling .all() on a filtered managed queryset will re-evaluate that queryset as if it has no filters:
This took a while to figure out and seems like bizarre behavior. Why is calling .all() on a queryset necessary when you can just iterate over it?
As a workaround, I have started using a custom ListSerializer that never calls .all(). Interested to hear if anybody else has run into this or tried using DRF Serializers together with the Prefetch object.
@tomchristie do we really need the queryset reevaluation ?
It definitively helps for new comers that don't fully understand QS but I'm a bit afraid we'll get a couple of similar issues - such as this one - at some point
This isn't a major blocker right now (e.g. we've been able to work around it with a custom ListSerializer and/or custom relation field that proxies a serializer)
However, perhaps there should be an setting that allows you to toggle this behavior, which can be on by default for newcomers per your example?
# Dealing with nested relationships, data can be a Manager,
# so, first get a queryset from the Manager if needed
iterable = data.all() if isinstance(data, (models.Manager, query.QuerySet)) else data
return [
self.child.to_representation(item) for item in iterable
]
The more I think about it the more I believe it is encouraging bad patterns (i.e. queryset evaluated where they shouldn't be)
@kevin-brown adding .all() creates a new queryset which by default isn't evaluated hence the second query. In most cases the .all().all() won't add additional DB request since the first queryset won't get a chance to be evaluated.
My question is specifically about the different query. I understand that it should be re-evaluated, which would be fine if it triggered the same query, but I don't understand why it's being evaluated using a different query.
Have closed #2727 as a duplicate of this, although possible that we can more broadly state the issue, as it's probably not justprefetch_related that's at issue, but anything else that can be lost when .all() is called on the queryset.
Issue a pull request with iterable = data.all() if isinstance(data, models.Manager) else data (Note that QuerySet is removed from the isinstance check.
Do any tests fail?
Check the blame/history on that line - when was it last modified and when was QuerySet added? What was the rationale at the time?
Note that #2727 includes a very trival example for demonstrating the behavior that doesn't rely on prefetch_related... #2727 (comment)
Activity
xordoquy commentedon Mar 17, 2015
Closing this as duplicate of #2442.
aleontiev commentedon Mar 17, 2015
@xordoquy this is actually a distinct issue that only comes up when you use the
Prefetchobject along with a queryset to filter the relation.My use case is providing a flexible GET API that provides filtering on secondary related resources.
xordoquy commentedon Mar 17, 2015
Will take time to investigate this further then
xordoquy commentedon Mar 17, 2015
This is to force the QS reevaluation when someone writes the view class such as:
Which means that the queryset will be evaluated at the class declaration rather than on per request basis if we didn't force the reevaluation.
xordoquy commentedon Mar 17, 2015
@tomchristie do we really need the queryset reevaluation ?
It definitively helps for new comers that don't fully understand QS but I'm a bit afraid we'll get a couple of similar issues - such as this one - at some point
aleontiev commentedon Mar 17, 2015
This isn't a major blocker right now (e.g. we've been able to work around it with a custom ListSerializer and/or custom relation field that proxies a serializer)
However, perhaps there should be an setting that allows you to toggle this behavior, which can be on by default for newcomers per your example?
lovelydinosaur commentedon Mar 17, 2015
@xordoquy Sorry, which one specifically?
xordoquy commentedon Mar 17, 2015
@tomchristie the one we have in serializers:
The more I think about it the more I believe it is encouraging bad patterns (i.e. queryset evaluated where they shouldn't be)
lovelydinosaur commentedon Mar 17, 2015
We certainly need it for the Manager case - I expect we do need it for the queryset case too, but it'd be worth look at the history for that line.
kevin-brown commentedon Mar 17, 2015
Is this something that's documented? It seems strange that calling
all()on a queryset multiple times will perform different queries.xordoquy commentedon Mar 17, 2015
@kevin-brown adding
.all()creates a new queryset which by default isn't evaluated hence the second query. In most cases the.all().all()won't add additional DB request since the first queryset won't get a chance to be evaluated.kevin-brown commentedon Mar 17, 2015
My question is specifically about the different query. I understand that it should be re-evaluated, which would be fine if it triggered the same query, but I don't understand why it's being evaluated using a different query.
I'm specifically referencing this
xordoquy commentedon Mar 17, 2015
@kevin-brown you probably have a point there. It should have been the very same request played another time. Probably an issue on the Django part.
2 remaining items
lovelydinosaur commentedon Jun 24, 2015
Have closed #2727 as a duplicate of this, although possible that we can more broadly state the issue, as it's probably not just
prefetch_relatedthat's at issue, but anything else that can be lost when.all()is called on the queryset.lovelydinosaur commentedon Jun 24, 2015
TODO to progress this issue:
iterable = data.all() if isinstance(data, models.Manager) else data(Note thatQuerySetis removed from theisinstancecheck.QuerySetadded? What was the rationale at the time?Note that #2727 includes a very trival example for demonstrating the behavior that doesn't rely on
prefetch_related... #2727 (comment)jpadilla commentedon Jun 25, 2015
Working on #3076 to hopefully progress this issue.
Merge pull request #3076 from jpadilla/issues/2704
lovelydinosaur commentedon Jun 25, 2015
Closed by #3076.
aleontiev commentedon Jun 25, 2015
Thanks for the fix guys :)
lovelydinosaur commentedon Jun 25, 2015
😄