用户工具

站点工具


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')

Null && Blank

  • Null: It is database-related. Defines if a given database column will accept null values or not.
  • Blank: It is validation-related. It will be used during forms validation, when calling form.is_valid().

From Django Tips #8 Blank or Null?

Template

Forms

django.txt · 最后更改: 2023/12/03 10:24 由 127.0.0.1