gpt4 book ai didi

python - 当我访问对象的属性时,Django 是否会访问数据库?

转载 作者:行者123 更新时间:2023-12-02 11:41:32 27 4
gpt4 key购买 nike

每次调用 Question.name 时,以下代码是否都会查询数据库?

class Question(models.Model):
name=models.CharField()
test=models.ForeignKey(Test)

questions = Question.objects.filter(test=some_test)
for question in questions:
question_name = question.name

我的 View 采用一组问题和用户响应并对工作表进行评分。我的目标是执行所有评分而不返回数据库,然后使用后台任务保存比较结果(字典),如果需要更长的时间也可以。我想消除任何不必要的数据库点击。

最佳答案

嗯,你的问题不清楚,但有一件事可以肯定,至少需要对数据库进行一次点击。事实上,在您的代码示例中您使用:

question_name = question.name

但如果 question 事先不是 Question 模型的实例,我认为此方法不起作用。

因此,考虑到您通过查询对数据库的初始命中来创建实例,question_name 可以根据需要多次重复使用,而无需访问数据库。看,这是数据库行的静态实例。

编辑

现在对于您的编辑来说,这不是相同的行为。要正确理解幕后发生的事情,您需要理解“惰性”的概念。事实上,由于 Django 中的查询集是惰性的,所以这一行:

questions = Question.objects.filter(test=some_test)

不会对数据库造成任何影响。查询集代表 SQL 查询集。因此,此时,由于您没有要求从数据库中获取某些内容,所以实际上尚未对其进行评估。这是所需的行为,因为它确保仅在需要时才访问数据库。作为documentation说以下是评估查询集的情况:

迭代

A QuerySet is iterable, and it executes its database query the first time you iterate over it.

切片

Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet, but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list. Slicing a QuerySet that has been evaluated also returns a list.

酸洗/缓存

repr(). A QuerySet is evaluated when you call repr() on it. This is for convenience in the Python interactive interpreter, so you can immediately see your results when using the API interactively.

len(). A QuerySet is evaluated when you call len() on it. This, as you might expect, returns the length of the result list.

list(). Force evaluation of a QuerySet by calling list() on it

bool(). Testing a QuerySet in a boolean context, such as using bool(), or, and or an if statement will cause the query to be executed

因此,如您所见,情况 1 适用于您的特定情况。迭代将导致对数据库的命中。

关于python - 当我访问对象的属性时,Django 是否会访问数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47214594/

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