Django 2.2 新特性清单

可以在 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_save 和 pre_save 信号将不会触发。
  • 如果数据量很大,可以指定 batch_szie 参数

migrations

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

针对 PG 数据库的优化

django.contrib.postgres

  • ordering 参数增加了 ArrayAgg 和 StringAgg 。可以针对 aggv 数据来做排序。
  • 新增的 BTreeIndex , HashIndex 和 SpGistIndex 类允许创建 B-Tree, hash, and SP-GiST 索引。
  • BrinIndex 现在有了一个 autosummarize 参数。
  • SearchQuery 的 search_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_'))
复制代码

猜你喜欢

转载自blog.csdn.net/c710473510/article/details/89552831
2.2
今日推荐