How do I select from multiple tables in one query with Django? How do I select from multiple tables in one query with Django? django django

How do I select from multiple tables in one query with Django?


Using select_related() will pre-populate the appropriate attributes:

Employee.objects.select_related()


It is an old question, let me provide a new answer.

Actually, you can do this:

employees = Employee.objects.all().values('id','name','company__name')

then, Django will automatically lookup Company class and find the company name for you.

on the template page, use {{employee.company__name}} then it will display the company name correctly.


I guess what you're looking for is the select_related method of your queryset. See the doc

select_related()

Returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. This is a performance booster which results in (sometimes much) larger queries but means later use of foreign-key relationships won't require database queries