本文介绍 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
的支持。
相关用法
- Python Wand negate()用法及代码示例
- Python Wand wavelet_denoise()用法及代码示例
- Python Wand local_contrast()用法及代码示例
- Python Wand sample()用法及代码示例
- Python Wand deskew()用法及代码示例
- Python Wand color()用法及代码示例
- Python Wand implode()用法及代码示例
- Python Wand adaptive_blur()用法及代码示例
- Python Wand unsharp_mask()用法及代码示例
- Python Wand gaussian_blur()用法及代码示例
- Python Wand polaroid()用法及代码示例
- Python Django WKBWriter.write_hex用法及代码示例
- Python Wand adaptive_sharpen()用法及代码示例
- Python Wand posterize()用法及代码示例
- Python Wand path_move()用法及代码示例
- Python Wand transform()用法及代码示例
- Python Wand shave()用法及代码示例
- Python Django WKTWriter.trim用法及代码示例
- Python Wand function()用法及代码示例
- Python Wand level()用法及代码示例
- Python Wand swirl()用法及代码示例
- Python Wand canny()用法及代码示例
- Python Django WKBReader用法及代码示例
- Python Wand rectangle()用法及代码示例
- Python Wand composite()用法及代码示例
注:本文由纯净天空筛选整理自djangoproject.com大神的英文原创作品 django.db.models.expressions.When。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。