How to make an Inner Join in django?

后端 未结 4 1924
野的像风
野的像风 2020-12-30 02:26

I want to show in an Html the name of the city, state, and country of a publication. But they are in different tables.

Here is my models.py

4条回答
  •  無奈伤痛
    2020-12-30 03:03

    You are probably looking for select_related, which is the natural way to achieve this:

    pubs = publication.objects.select_related('country', 'country_state', 'city')
    

    You can check the resulting SQL via str(pubs.query), which should result in output along the following lines (the example is from a postgres backend):

    SELECT "publication"."id", "publication"."title", ..., "country"."country_name", ...  
    FROM "publication" 
    INNER JOIN "country" ON ( "publication"."country_id" = "country"."id" ) 
    INNER JOIN "countrystate" ON ( "publication"."countrystate_id" = "countrystate"."id" ) 
    INNER JOIN "city" ON ( "publication"."city_id" = "city"."id" ) 
    

    The returned cursor values are then translated into the appropriate ORM model instances, so that when you loop over these publications, you access the related tables' values via their own objects. However, these accesses along the pre-selected forward relations will not cause extra db hits:

    {% for p in pubs %}
         {{ p.city.city_name}}  # p.city has been populated in the initial query
         # ...
    {% endfor %}
    

提交回复
热议问题