Django 2.2 新特性清单

1,191 阅读4分钟

原文档地址:docs.djangoproject.com/en/2.2/rele…

最主要feature:Model Conatrains

可以在 model 的 Meta 中定义一个 constrains 列表。比如下面这个例子,添加了一个age字段数据必须大于等于18的限制。

注意:不能在 AbstractModel 类里面定义constrains,因为每个 constrain都必须要有一个唯一的名字。如果在AbstractModel中定义的话,势必会重复。

from django.db import models

class Customer(models.Model):
    age = models.IntegerField()

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
        ]

知识点回顾:models.Q 查询

models.Q 可以用来组合产生复杂的查询语句,比如 OR 查询:

queryset = User.objects.filter(
    Q(first_name__startswith='R') | Q(last_name__startswith='D')
)

AND 查询:

queryset = User.objects.filter(
    Q(first_name__startswith='R') & Q(last_name__startswith='D')
)

first_name‘R’开头, 但是 last_name 不以Z开头:

 queryset = User.objects.filter(
    Q(first_name__startswith='R') & ~Q(last_name__startswith='Z')
)

详情情见:

class CheckConstraint

check

必填参数。

需要传入一个Q 对象,表明你需要怎样的 constrain 要求,比如CheckConstraint(check=Q(age__gte=18), name='age_gte_18')确保age字段用于不会小于18.

name

必填参数。必须是唯一的。

class UniqueConstraint

fields

对哪些 fields 做唯一限制。比如UniqueConstraint(fields=['room', 'date'], name='unique_booking')确保每个 room 一天只能被预订一次。

name

同上,必须是唯一的。

condition

满足什么条件时才要求强制 constrain 条件。

测试用例:

model 相关

automatic transaction的变化

2.2发布日志里面一个不起眼的地方写了这样一句:

Django no longer always starts a transaction when a single query is being performed, such as Model.save(), QuerySet.update(), and Model.delete(). This improves the performance of autocommit by reducing the number of database round trips.

也就是说 django 不再和之前一样,每个 query(比如 save,update,delete) 都会开启一个 transaction。这样可以通过减少 django <-> 数据库往返次数来提高效率。

Index.condition

文档

考虑到这样的应用场景:table 很大,但是 query 只会查询一小部分的数据。为所有数据项都建一个索引是没必要的,这时候就可以针对某一部分特定数据建立索引。

比如下面这个例子:

indexes = [
    models.Index(
        fields=['username'],
        condition=models.Q(age__gte=30),
        name='idx_username_age_gte30'
    )
]

将只会为年龄大于30岁的用户在username这个字段上建立索引。

Index.condition 底层支持依赖于数据库的partial indexes。 而MySQL、MariaDB、Oracle都不支持partial indexes,所以这些数据库会直接忽略掉。

bulk_create

增加了一个ignore_conflicts参数,设置为 TRUE 的时候告诉数据库忽略由于 constrain 产生的错误。

bulk_update

bulk_update(objs, fields, batch_size=None)

需要 update 大量数据的时候很有用。

>>> objs = [
...    Entry.objects.create(headline='Entry 1'),
...    Entry.objects.create(headline='Entry 2'),
... ]
>>> objs[0].headline = 'This is entry 1'
>>> objs[1].headline = 'This is entry 2'
>>> Entry.objects.bulk_update(objs, ['headline'])

这样会比使用一个 for 循环一个一个调用update()方法速度更快。

有几点需要注意:

  • save()方法不会被调用,所以post_savepre_save信号将不会触发。
  • 如果数据量很大,可以指定batch_szie 参数

migrations

新增了一个--plan命令行参数,用来查看 django 将要执行什么数据库修改操作。

针对 PG 数据库的优化

django.contrib.postgres

  • ordering参数增加了ArrayAggStringAgg。可以针对 aggv 数据来做排序。
  • 新增的BTreeIndex, HashIndexSpGistIndex 类允许创建 B-Tree, hash, and SP-GiST 索引。
  • BrinIndex现在有了一个autosummarize参数。
  • SearchQuerysearch_type做了些变化。

HttpRequest

新增了HttpRequest.headers,以便更方便地获取请求头信息。

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

>>> request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
>>> request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)

之前需要通过 request.META获取,相对要麻烦了很多。在2.2之前的版本,如果你想要获取所有的 HTTP 请求头的话,可以这么获取:

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))

其他特性

其他琐碎的东西还有很多,比如:

  • collectstatic --ignore PATTERN选项,忽略指定模式的静态资源。
  • inspectdb有了更丰富的功能。
  • Tests 新功能。

详细的,还是去看官方的文档吧。此外还提到了一些往前不兼容的改变,如果你的项目里面用到了,也需要注意注意。

我的公众号:全栈不存在的