Django select related in raw request

后端 未结 3 1899

How to make \"manual\" select_related imitation to avoid undesirable DB hits?

we have:

class Country:
    name = CharField()
class City:
    country          


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 10:35

    I'm not sure if you can do this. As an alternative, you can select individual fields from the country table and access them on each instance.

    cities = City.objects.raw("select city.*, name as country_name from city inner join country on city.country_id = country.id where name = 'london'")
    
    city = cities[0]
    # this will not hit the database again
    city.country_name
    

提交回复
热议问题