本文介紹 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。