Opened 2 months ago

Last modified 2 days ago

#28600 assigned New feature

Add prefetch related support to RawQuerySet

Reported by: Adnan Umer Owned by: Adnan Umer
Component: Database layer (models, ORM) Version: master
Severity: Normal Keywords:
Cc: Дилян Палаузов Triage Stage: Accepted
Has patch: yes Needs documentation: yes
Needs tests: yes Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

When using custom raw SQL queries with Django ORM,

  • There is no support to prefetch related models to increase performance
  • Query results need to be cached manually

Change History (7)

comment:1 Changed 2 months ago by Adnan Umer

Owner: changed from nobody to Adnan Umer
Status: newassigned

comment:2 Changed 8 weeks ago by Tim Graham

Has patch: unset
Summary: Prefetch Related Support in RawQuerySetAdd prefetch related support to RawQuerySet
Triage Stage: UnreviewedAccepted

Tentatively accepting, although I haven't looked into the history to understand if there's a design reason why it's not implemented. A post on django-users suggests that using prefetch_related_objects() (which has since been documented as a public API) works.

I'm unchecking "Has patch" as I don't see a patch anywhere. If there's a patch somewhere, please provide a link.

comment:3 Changed 8 weeks ago by Adnan Umer

Has patch: set
Needs tests: set

Here is the link to PR that enabled this feature.

Last edited 6 weeks ago by Adnan Umer (previous) (diff)

comment:4 Changed 6 weeks ago by Дилян Палаузов

Would you mind implementing the same for bulk_create() #28692?

comment:5 Changed 6 weeks ago by Дилян Палаузов

Cc: Дилян Палаузов added

comment:6 in reply to:  4 Changed 6 weeks ago by Adnan Umer

Replying to Дилян Палаузов:

Would you mind implementing the same for bulk_create() #28692?

Once someone accept the ticket, I'll post commit solution of that. BTW you can temporarily avoid that situation this way

models = ModelA.objects.bulk_create([ModelA(...), ModelA(...), ModelA(...)])
from django.db.models import prefetch_related_objects
prefetch_related_objects(models, 'b')
for m in models:
        print(m.b.description)  # No more extra SELECT query here
Last edited 6 weeks ago by Adnan Umer (previous) (diff)

comment:7 Changed 2 days ago by Asif Saifuddin Auvi

Needs documentation: set
Patch needs improvement: set
Note: See TracTickets for help on using tickets.
Back to Top