prefetch_related() ForeignKey reverse lookup in Django?
Asked Answered
S

1

1

I've got two models:

class Company(models.Model):
    ...

class Supplier(models.Model):
  company = models.ForeignKey(Company, null=True, related_name="suppliers")

How to get all Companies with their related Suppliers?

I've tried:

Company.objects.prefetch_related('suppliers') 
Company.objects.prefetch_related('supplier_set') 
Company.objects.prefetch_related('suppliers').all()
...

What I'm doing wrong?

Thank you

Sacco answered 18/11, 2016 at 0:20 Comment(0)
M
2

prefetch_related just adds the SQL query to get the suppliers so that when you do company.suppliers.all() you don't incur another SQL hit on top of Company.objects.all(). You can access the suppliers normally thereafter:

companies = Company.objects.all().prefetch_related('suppliers')

for company in companies:
    # Does not require a new SQL query
    suppliers = company.suppliers.all()
Momentum answered 18/11, 2016 at 2:31 Comment(2)
Any way to include additional SQL query? I need to fetch companies with suppliers to use it in templates after. Tried select_related('suppliers'), however I get: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'suppliers'. Choices are: (none)Sacco
Huh, that's a separate issue. You're using select_related on Company? Do you still have related_name='suppliers' on the Supplier model?Momentum

© 2022 - 2024 — McMap. All rights reserved.