Home > Software design >  Django: usage of prefetch_related
Django: usage of prefetch_related

Time:11-07

I have some models with this relation:

EmailReport --many-to-many--> PaymentReport --foreign-key--> Shop --many-to-many--> users

Now I want to reach the users from EmailReport. I tried this query but failed:

query = models.EmailReport.objects.prefetch_related('payment_report').prefetch_related('shop__users').filter(pk__in=ids)

Anyone knows the correct query?

Update:

Thanks to @bartosz-stasiak The query is:

objects= EmailReport.objects.prefetch_related('payment_report__shop__users').filter(pk__in=ids)

But how can I access to the prepetch users? Tried this and failed:

objects= EmailReport.objects.prefetch_related('payment_report__shop__users').filter(pk__in=ids)
for object in objects:
   object.users.all()

CodePudding user response:

Probably:

email_reports = EmailReport.objects.prefetch_related('payment_report__shop__users').filter(pk__in=ids)

(That are ids here? Users ids or EmailReport ids?)

This shoud be minimal amount of queries. Just remember that you can't do further filtering or it will break the prefetch.

Then there are few ways to get the users. The most simple will probably be: (but can be unefficient)

users_from_query = []
for email_report in email_reports:
    for pr in email_report.payment_report.all()
        users_from_query.extend(pr.shop.users.all())
  • Related