Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.
select_related
用于解决ORM中的n+1问题(即在包含外键的对象中执行查询时,会查询n+1次)。
假设有数据库模型如下:
class User(models.Model): name = models.CharField(max_length=255) class Article(models.Model): title = models.CharField(max_length=255) content = models.TextField() creator = models.ForeignField(User)
在一个列表中,简单地 查询文章列表及其作者,将会查询n+1次:
{% for article in articles %} <h2>{{ article.title }}</h2> <p>author: {{ article.creator.name }}</p> {% endfor %}
然而使用 SQL
语言使用 inner join
只需要查询一次即可。
Django orm 使用 select_related
来解决这个问题:
articles = Article.objects.all().select_related('creator')