Django(和其他MVC/ORM)中的延迟加载关系 [英] Lazy loading relationships in Django (and other MVCs/ORMs)

查看:76
本文介绍了Django(和其他MVC/ORM)中的延迟加载关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有兴趣了解如何在Django之类的框架中实现延迟加载.什么时候决定执行加入?有没有一种方法可以强制在Django中快速加载?在某些时候您需要强迫Django急于加载吗?

Interested in knowing how lazy loading is achieved in frameworks like Django. When is the decision made to perform the join? And is there a way to force eager loading in Django? Are there times when you would need to force Django to eager load?

推荐答案

通常的答案是,当您实际要求一些记录时,Django会决定执行查询.通常,这意味着迭代查询集(for record in queryset:)或使用list()内置函数将查询集转换为列表.

The general answer is that Django makes the decision to perform the query when you actually ask for some records. Most commonly this means iterating over the queryset (for record in queryset:) or using the list() built-in function to convert the queryset to a list.

有关更多详细信息,请参见评估QuerySet时来自官方文档.

See When QuerySets are evaluated for more specifics from the official docs.

它通过在django/db/models/query.py中定义一个名为QuerySet的类来实现此目的,其中对__repr____getitem____iter__之类的特殊方法进行了编码以完成正确的事情.

It accomplishes this by defining a class, called QuerySet in django/db/models/query.py, where the special methods like __repr__, __getitem__ and __iter__ are coded to do the right thing.

如果您需要强制进行紧急加载,只需在queryset上运行内置的Python列表函数,例如:

If you need to force eager loading just run the built-in Python list function on the queryset, like:

qs = SomeModel.objects.all()
ql = list(qs)

此对list()的调用将执行数据库查询并将所有对象加载到内存中.您很少需要执行此操作,但是一种情况是,您需要在模板中的多个位置使用查询结果.转换为列表并在模板上下文中传递列表将只执行一次查询,而不是对您迭代的模板中的每个位置执行一次查询.

This call to list() will perform the DB query and load all of the objects into memory. It should be pretty rare that you need to do this, but one case is when you need to use the query results in more than one place in your templates. Converting to list and passing the list in your template context will perform the query only once instead of once for every place in your template you iterate.

这篇关于Django(和其他MVC/ORM)中的延迟加载关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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