當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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