当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Django When用法及代码示例


本文介绍 django.db.models.expressions.When 的用法。

声明

class When(condition=None, then=None, **lookups)

When() 对象用于封装条件及其结果以在条件表达式中使用。使用When() 对象类似于使用 filter() 方法。可以使用字段查找、 Q 对象或具有 output_field BooleanField Expression 对象来指定条件。使用then 关键字提供结果。

在 Django 4.0 中更改:

添加了对查找表达式的支持。

一些例子:

>>> from django.db.models import F, Q, When
>>> # String arguments refer to fields; the following two examples are equivalent:
>>> When(account_type=Client.GOLD, then='name')
>>> When(account_type=Client.GOLD, then=F('name'))
>>> # You can use field lookups in the condition
>>> from datetime import date
>>> When(registered_on__gt=date(2014, 1, 1),
...      registered_on__lt=date(2015, 1, 1),
...      then='account_type')
>>> # Complex conditions can be created using Q objects
>>> When(Q(name__startswith="John") | Q(name__startswith="Paul"),
...      then='name')
>>> # Condition can be created using boolean expressions.
>>> from django.db.models import Exists, OuterRef
>>> non_unique_account_type = Client.objects.filter(
...     account_type=OuterRef('account_type'),
... ).exclude(pk=OuterRef('pk')).values('pk')
>>> When(Exists(non_unique_account_type), then=Value('non unique'))
>>> # Condition can be created using lookup expressions.
>>> from django.db.models.lookups import GreaterThan, LessThan
>>> When(
...     GreaterThan(F('registered_on'), date(2014, 1, 1)) &
...     LessThan(F('registered_on'), date(2015, 1, 1)),
...     then='account_type',
... )

请记住,这些值中的每一个都可以是一个表达式。

注意

由于 then 关键字参数是为 When() 的结果保留的,因此如果 Model 具有名为 then 的字段,则可能存在冲突。这可以通过两种方式解决:

>>> When(then__exact=0, then=1)
>>> When(Q(then=0), then=1)
在 Django 3.2 中更改:

添加了对使用 condition 参数和 lookups 的支持。

相关用法


注:本文由纯净天空筛选整理自djangoproject.com大神的英文原创作品 django.db.models.expressions.When。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。