Django ORM INNER JOIN

14,434

Based on the information in your comment responding to pdxwebdev (that you have a foreign key field declared) this is simple. Django automates much of the join behavior needed for foreign key relationships.

To precisely replicate that query, including selecting only two fields from the join, any of values, values_list or only should do it depending on exactly what Python objects you want to get back. Eg, here's a query using values to retrieve an iterable queryset of dictionaries:

Establecimiento.objects.values('nombre', 'categoria__titulo')

values_list will retrieve tuples instead of dictionaries, and only will retrieve Establecimiento instances on which all model fields other than those two are deferred (they have not been retrieved from the database but will be looked up as needed).

When you use __ to follow a foreign key relationship like that, Django will do the inner join automatically.

You can also use select_related on a queryset to ask it to do the join even when you're not retrieving specific fields. EG:

Establecimiento.objects.select_related('categoria')

This should produce a query of SELECT * from ..., and return a queryset of Establecimiento instances that have their categoria data already loaded into memory.

Share:
14,434
user3236034
Author by

user3236034

Updated on June 04, 2022

Comments

  • user3236034
    user3236034 almost 2 years

    I have not been able to do this query with Django ORM. how to make a inner join, how to do this query and return only the columns I want?

    SELECT     establecimiento.nombre, categoria.titulo
    FROM         establecimiento INNER JOIN
                          categoria ON establecimiento.categoria = categoria.id