gpt4 book ai didi

django - Django 查询如何工作?

转载 作者:行者123 更新时间:2023-12-03 11:33:47 26 4
gpt4 key购买 nike

我的模型是这样设计的

class Warehouse:
name = ...
sublocation = FK(Sublocation)

class Sublocation:
name = ...
city = FK(City)

class City:
name = ..
state = Fk(State)

现在,如果我抛出一个查询。
wh = Warehouse.objects.value_list(['name', 'sublocation__name', 
'sublocation__city__name']).first()

它返回正确的结果,但在内部它抛出了多少查询? django 是在一个请求中获取数据吗?

最佳答案

Django 只对数据库进行一次查询以获取您描述的数据。
当你这样做时:

wh = Warehouse.objects.values_list(
'name', 'sublocation__name', 'sublocation__city__name').first()

它转换为以下查询:
SELECT "myapp_warehouse"."name", "myapp_sublocation"."name", "myapp_city"."name"
FROM "myapp_warehouse" INNER JOIN "myapp_sublocation"
ON ("myapp_warehouse"."sublocation_id" = "myapp_sublocation"."id")
INNER JOIN "myapp_city" ON ("myapp_sublocation"."city_id" = "myapp_city"."id")'

它在单个查询中获得结果。您可以像这样计算 shell 中的查询数量:
from django.db import connection as c, reset_queries as rq

In [42]: rq()

In [43]: len(c.queries)
Out[43]: 0

In [44]: wh = Warehouse.objects.values_list('name', 'sublocation__name', 'sublocation__city__name').first()

In [45]: len(c.queries)
Out[45]: 1

关于django - Django 查询如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com