Repository navigation
ManyRelatedField causes n+1 issue on to_internal_value #8919
Unanswered
kandji-gregg
asked this question in
Potential Issue
Replies: 3 comments 1 reply
|
Unless I'm misunderstanding, this should be solved by using |
1 reply
|
I just ran into this issue. |
0 replies
|
I would happy to see a PR that fix and don't change any existing behaviour in DRF |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Passing
many=Trueas a param for a foreign-key relation causes drf to use a ManyRelatedField instead. But the problem is that whento_internal_valueis called for a ManyRelatedField it loops through each item in data and passes it to the child_relation's toto_internal_value. While this works, every item in the list is individually fetched from the DB, even though it could likely could be queried in bulk.It's most obvious when using a
PrimaryKeyRelatedFieldand for every ID in the relation, it fetches the object using queryset.get(pk=data) for every id, even if it's 1000. Instead, we could easily doqueryset.get(pk__in=data)to retrieve the data.I suggest adding a new optional class method for Fields that bulk queries for the field. Code for to_internal_value in ManyRelated field could look like:
All reactions