Opened 8 years ago
Closed 8 years ago
#27228 closed Bug (invalid)
prefetch_related with select_related takes a lot of query
Reported by: | aki33524 | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.10 |
Severity: | Normal | Keywords: | prefetch_related select_related |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
mdoels.py
class A(models.Model): pass class B(models.Model): pass class C(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B)
python manage.py shell
for i in range(100): a = A() a.save() b = B() b.save() C(a=a, b=b).save() queryset = A.objects.prefetch_related('c_set') for v in queryset: print(v.c_set.count()) # 2 queries queryset = C.objects.select_related() for v in queryset: print(v.a.id) # 2 queries l = A.objects.prefetch_related(Prefetch('c_set', queryset=C.objects.select_related('b'))) for v in l: print(v.c_set.filter(b__id=1)) # 100 queries
I run this code in Django1.10.1, but the last takes a lot of queries. I think that the last can take only few queries.
Change History (1)
comment:1 by , 8 years ago
Component: | Uncategorized → Database layer (models, ORM) |
---|---|
Resolution: | → invalid |
Status: | new → closed |
Note:
See TracTickets
for help on using tickets.
See the note in the prefetch_related() docs ("Remember that, as always with QuerySets, ...").