用户工具

站点工具


django

这是本文档旧的修订版!


Django

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

View

Model

select_related 用于解决ORM中的n+1问题(即在包含外键的对象中执行查询时,会查询n+1次)。

假设有数据库模型如下:

models.py
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次:

index.html
{% 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')

Template

Forms

django.1500205526.txt.gz · 最后更改: 2023/12/03 10:24 (外部编辑)