[Fixed]-How do I select from multiple tables in one query with Django?

35👍

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

Employee.objects.select_related()

20👍

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 {{employees.company__name}} then it will display the company name correctly.

👤Ken

10👍

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

2👍

With raw queries

    qry1 = "SELECT c.car_name, p.p_amount FROM pay p, cars c where p.user_id=%s;"

    cars = Cars.objects.raw(qry1, [user_id])

Leave a comment