我有一个这样的模型......
class Model():
header = CharField()
tagline = CharField()
menubutton1 = Charfield()
menubutton2 = CharField()
page1 = CharField()
page2 = CharField()
页眉和标语进入每个模板,但 page1 和 page2 文本只会进入它们对应的页面。我做了一个查询,然后将它们包含在许多不同的 View 中,所以我想知道是否所有数据都是从数据库中提取并在进行查询时或在模板中调用数据时实际传输的?
请您参考如下方法:
QuerySets are lazy ( constructed, filtered, sliced, and generally passed around without actually hitting the database) ,但是一旦获取模型,它就会从数据库中加载模型的所有字段。
延迟()
但是您可以使用 .defer()在查询集上排除在评估查询集时从数据库加载的字段。它有效地延迟这些字段的加载。
In some complex data-modeling situations, your models might contain a lot of fields, some of which could contain a lot of data (for example, text fields), or require expensive processing to convert them to Python objects. If you are using the results of a queryset in some situation where you don’t know if you need those particular fields when you initially fetch the data, you can tell Django not to retrieve them from the database.
例如您希望作为第 1 页上下文的查询集排除字段 page2
models_for_page_1 = Model.objects.defer('page2')
当上面的查询集被评估时,它将获取除 page2 之外的所有字段
Each deferred field will be retrieved from the database if you access that field (one at a time, not all the deferred fields at once).
如果您不通过该字段的延迟加载从该查询集访问模型上的 page2,它将永远不会加载,但如果您访问它,它将单独加载当您访问它时。
只要页面 1 从不访问 Model.page2,这就可以满足您的要求。
仅()
这是 defer() 的补充,它只获取列出的字段,所以对你来说例如:
models_for_page_1 = Model.objects.only('header', 'tagline', ..., 'page1')
defer()/only()和values()的区别
defer() 和 only() 返回模型实例,而 values() 返回包含值的字典
