Django select related in raw request

后端 未结 3 1932

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:42

    Not sure if you still need this, but I solved it starting with Alasdair's answer. You want to use the info from the query to build the model or it'll still fire additional queries when you try to access the foreign key field. So in your case, you'd want:

        cities = list(City.objects.raw("""
            SELECT
                city.*, country.name as countryName
            FROM
                cities INNER JOIN country ON city.country_id = country.id
            WHERE
                city.name = 'LONDON"""))
        for city in cities:
            city.country = Country(name=city.countryName)
    

    The line that assigns the country doesn't hit the database, it's just creating a model. Then after that, when you access city.country it won't fire another database query.

提交回复
热议问题