Django在原始请求中选择相关 [英] Django select related in raw request

查看:92
本文介绍了Django在原始请求中选择相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使手动选择相关模仿以避免不必要的数据库命中?

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

我们有:

class Country:
    name = CharField()
class City:
    country = models.ForeignKey(Country)
    name = models.CharField()

cities = City.objects.raw("select * from city inner join country on city.country_id = country.id where name = 'london'")

#this will hill hit DB
print cities[0].country.name

如何告诉django相关模型已经被提取。

How to tell django that related models are already fetched.

推荐答案

不知道如果你还需要这个,但是我从Alasdair的答案开始解决了。您希望使用查询中的信息构建模型,或者在尝试访问外键字段时仍会触发其他查询。所以在你的情况下,你会想:

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)

分配国家的行不会打到数据库,它只是创建一个模型。然后,当您访问 city.country 它将不会触发另一个数据库查询。

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.

这篇关于Django在原始请求中选择相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆