ManyRelatedField causes n+1 issue on to_internal_value #8919
Replies: 3 comments 1 reply
-
Unless I'm misunderstanding, this should be solved by using |
Beta Was this translation helpful? Give feedback.
-
I just ran into this issue. |
Beta Was this translation helpful? Give feedback.
-
I would happy to see a PR that fix and don't change any existing behaviour in DRF |
Beta Was this translation helpful? Give feedback.
-
Passing
many=True
as a param for a foreign-key relation causes drf to use a ManyRelatedField instead. But the problem is that whento_internal_value
is 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
PrimaryKeyRelatedField
and 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:
Beta Was this translation helpful? Give feedback.
All reactions