user2734
user2734

Reputation: 11

prefetch_related() ForeignKey reverse lookup in Django?

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

Upvotes: 1

Views: 2980

Answers (1)

Jens Astrup
Jens Astrup

Reputation: 2454

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()

Upvotes: 2

Related Questions