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
Performance issue: N+1 queries and slow validation when using many=True with serializers containing relational fields #9607
The problem lies in the implementation of ManyrelatedField which is extremely simple and does not implement any kind of DB-level optimization. The same problem is in ListSerializer.create method. To keep those elements "simple" they just delegate DB operations to children, but this is not-optimal when there are many elements.
This is not technically a bug, because it does what it is expected, yet it is a bad usage of resources and should be addressed.
Reacted by Asif Saif Uddin {"Auvi":"অভি"} and Kushal Baral
The behavior you're observing is due to how Django's PrimaryKeyRelatedField interacts with the database when many=True is used. Each item in the list of primary keys results in an individual query to fetch the corresponding MachineModel instance. This can lead to N+1 query problems, where N is the number of related objects being fetched.
Validation Per Instance:
PrimaryKeyRelatedField :
fetches each related object separately to ensure it exists and matches the given queryset.
The queries you see are part of this validation process.
No Bulk Query:
By default, PrimaryKeyRelatedField does not perform a single bulk query to fetch all related objects at once.
This may be handled like it is done in Django core MultipleChoiceField: build a "bulk" select and than check if every provided key is in the returned queryset:
And there's also a approach suggested here: #8919 (comment) which is to try a single self.child_relation.bulk_to_internal_value(data) call before falling back to the current
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
I encountered another performance issue.
When I use an EventSerializer with many=True to validate around 1,000 events, and the serializer includes two SlugRelatedFields and one PrimaryKeyRelatedField, the validation process takes around 17 seconds.
Each row triggers approximately 3 database queries, which leads to a severe N+1 query problem during validation.
changed the title [-]Question about PrimaryKeyRelatedField with `many=True`[/-][+]Performance issue: N+1 queries and slow validation when using many=True with serializers containing relational fields[/+]on Oct 17, 2025
On the second case (validating ~1,000 events with two SlugRelatedFields and a PrimaryKeyRelatedField): that's ListSerializer validating rows one at a time, so each related field runs one query per row.
drf-batch handles this case. It collects each related field's keys across the whole many=True payload, runs one in_bulk query per field, then validates every row in memory:
fromdrf_batchimportBatchRelatedField, BatchSerializerclassEventSerializer(BatchSerializer):
venue=BatchRelatedField(lookup="slug", queryset=Venue.objects.filter(active=True)) # was SlugRelatedFieldcategory=BatchRelatedField(lookup="slug") # was SlugRelatedFieldowner=BatchRelatedField() # was PrimaryKeyRelatedFieldclassMeta:
model=Eventfields= ("id", "venue", "category", "owner", "name")
serializer=EventSerializer(data=rows, many=True, context={"request": request})
serializer.is_valid(raise_exception=True)
That's one query per related field for the whole payload, not one per row. It works from a plain APIView and requires Python 3.11+, Django 5.2+ and DRF 3.15+.
It does not cover the original case here: PrimaryKeyRelatedField(many=True) on a M2M (ManyRelatedField). That lookup happens inside ManyRelatedField itself.
Activity
browniebroke commentedon Dec 17, 2024
Are you prefeching the relationship in your view? You'll need to use Django's
prefetch_related().cheehong1030 commentedon Dec 17, 2024
This is for validation purposes, so I cannot use
prefetch_related.Here is the serializer:
Here is my model using a many-to-many relationship:
So, how should I handle prefetch the relations
browniebroke commentedon Dec 17, 2024
Ah ok, I thought you were doing a read-only request, I didn't realise it was a PUT request. I don't know the answer in this case.
cheehong1030 commentedon Dec 17, 2024
This might be a bug. It seems that the case of
PrimaryKeyRelatedFieldwithmany=Truewasn't considered.sevdog commentedon Dec 23, 2024
The problem lies in the implementation of
ManyrelatedFieldwhich is extremely simple and does not implement any kind of DB-level optimization. The same problem is inListSerializer.createmethod. To keep those elements "simple" they just delegate DB operations to children, but this is not-optimal when there are many elements.This is not technically a bug, because it does what it is expected, yet it is a bad usage of resources and should be addressed.
cheehong1030 commentedon Dec 24, 2024
Maybe this could open a PR to optimize it.
sreedhar742 commentedon Jan 5, 2025
The behavior you're observing is due to how Django's PrimaryKeyRelatedField interacts with the database when many=True is used. Each item in the list of primary keys results in an individual query to fetch the corresponding MachineModel instance. This can lead to N+1 query problems, where N is the number of related objects being fetched.
Validation Per Instance:
PrimaryKeyRelatedField :
fetches each related object separately to ensure it exists and matches the given queryset.
The queries you see are part of this validation process.
No Bulk Query:
By default, PrimaryKeyRelatedField does not perform a single bulk query to fetch all related objects at once.
cheehong1030 commentedon Jan 6, 2025
So, is there no solution for this issue?
sevdog commentedon Jan 7, 2025
This may be handled like it is done in Django core MultipleChoiceField: build a "bulk" select and than check if every provided key is in the returned queryset:
https://github.com/django/django/blob/40d5516385448a73426aad396778f369a363eda9/django/forms/models.py#L1622-L1658
This is not an hard task, since an implementation is ready for use for the same use-case.
tomviner commentedon Jan 9, 2025
We hit this today. Searching the repo I see an attempt was made a while back:
And there's also a approach suggested here: #8919 (comment) which is to try a single
self.child_relation.bulk_to_internal_value(data)call before falling back to the current[ self.child_relation.to_internal_value(item) for item in data ]stale commentedon Jul 19, 2025
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
cheehong1030 commentedon Oct 17, 2025
I encountered another performance issue.
When I use an EventSerializer with many=True to validate around 1,000 events, and the serializer includes two SlugRelatedFields and one PrimaryKeyRelatedField, the validation process takes around 17 seconds.
Each row triggers approximately 3 database queries, which leads to a severe N+1 query problem during validation.
[-]Question about PrimaryKeyRelatedField with `many=True`[/-][+]Performance issue: N+1 queries and slow validation when using many=True with serializers containing relational fields[/+]p-r-a-v-i-n commentedon Nov 18, 2025
fixing this may go against DRF’s policy of not altering or overriding Django ORM behavior ?
auvipy commentedon Nov 20, 2025
well it depends
Fix encode#9607: Batch queryset lookup for PrimaryKeyRelatedField wit…
matink112 commentedon Nov 1, 2026
On the second case (validating ~1,000 events with two
SlugRelatedFields and aPrimaryKeyRelatedField): that'sListSerializervalidating rows one at a time, so each related field runs one query per row.drf-batch handles this case. It collects each related field's keys across the whole
many=Truepayload, runs onein_bulkquery per field, then validates every row in memory:That's one query per related field for the whole payload, not one per row. It works from a plain
APIViewand requires Python 3.11+, Django 5.2+ and DRF 3.15+.It does not cover the original case here:
PrimaryKeyRelatedField(many=True)on a M2M (ManyRelatedField). That lookup happens insideManyRelatedFielditself.Disclosure: I'm the author. Docs PR: #10092.
The field names (venue, category, owner, name) are placeholders, because the commenter never shared theirs.