0

工作一个 django 项目并试图加快调用速度。我注意到 Django 会自动执行第二个查询来评估任何外键关系。例如,如果我的模型看起来像:

Model Person:
    name = model.CharField("blah")

Model Address:
    person = model.ForeignKey(Person)

然后我做:

p1 = Person("Bob")
address1 = Address(p1)
print (p1.id) #let it be 1 cause it is the first entry

然后当我打电话时:

address1.objects.filter(person_id = "1")

我得到:

查询 #1:选择addressid,address.person_idaddress

查询 #2:选择personid,person.nameperson

我想摆脱第二个电话,查询#2。我曾尝试使用 django 文档中的“延迟”,但这不起作用(实际上它会进行更多调用)。“价值观”是一种可能性,但在实际实践中,我想提取更多领域。我唯一想做的就是不评估外键。我很乐意取回 person_id,或者不取回。这大大减少了运行时间,尤其是当我执行如下命令时:Address.objects.all(),因为 Django 会评估每个外键。

4

1 回答 1

0

Having just seen your other question on the same issue, I'm going to guess that you have defined a __unicode__ method that references the ForeignKey field. If you query for some objects in the shell and output them, the __unicode__ method will be called, which requires a query to get the ForeignKey. The solution is to either rewrite that method so it doesn't need that reference, or - as I say in the other question - use select_related().

Next time, please provide full code, including some that actually demonstrates the problem you are having.

于 2013-03-18T21:28:13.953 回答