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


Python Django Case用法及代碼示例

本文介紹 django.db.models.expressions.Case 的用法。

聲明

class Case(*cases, **extra)

Case() 表達式類似於 Python 中的 if elif else 語句。提供的When() 對象中的每個condition 都按順序進行評估,直到評估為真實值。返回匹配的When() 對象中的result 表達式。

一個例子:

>>>
>>> from datetime import date, timedelta
>>> from django.db.models import Case, Value, When
>>> Client.objects.create(
...     name='Jane Doe',
...     account_type=Client.REGULAR,
...     registered_on=date.today() - timedelta(days=36))
>>> Client.objects.create(
...     name='James Smith',
...     account_type=Client.GOLD,
...     registered_on=date.today() - timedelta(days=5))
>>> Client.objects.create(
...     name='Jack Black',
...     account_type=Client.PLATINUM,
...     registered_on=date.today() - timedelta(days=10 * 365))
>>> # Get the discount for each Client based on the account type
>>> Client.objects.annotate(
...     discount=Case(
...         When(account_type=Client.GOLD, then=Value('5%')),
...         When(account_type=Client.PLATINUM, then=Value('10%')),
...         default=Value('0%'),
...     ),
... ).values_list('name', 'discount')
<QuerySet [('Jane Doe', '0%'), ('James Smith', '5%'), ('Jack Black', '10%')]>

Case() 接受任意數量的 When() 對象作為單獨的參數。其他選項使用關鍵字參數提供。如果沒有條件評估為 TRUE ,則返回帶有 default 關鍵字參數的表達式。如果未提供 default 參數,則使用 None

如果我們想根據 Client 的使用時間更改之前的查詢以獲取折扣,我們可以使用查找來實現:

>>> a_month_ago = date.today() - timedelta(days=30)
>>> a_year_ago = date.today() - timedelta(days=365)
>>> # Get the discount for each Client based on the registration date
>>> Client.objects.annotate(
...     discount=Case(
...         When(registered_on__lte=a_year_ago, then=Value('10%')),
...         When(registered_on__lte=a_month_ago, then=Value('5%')),
...         default=Value('0%'),
...     )
... ).values_list('name', 'discount')
<QuerySet [('Jane Doe', '5%'), ('James Smith', '0%'), ('Jack Black', '10%')]>

注意

請記住,條件是按順序計算的,因此在上麵的示例中,即使第二個條件同時匹配 Jane Doe 和 Jack Black,我們也會得到正確的結果。這就像 Python 中的 if elif else 語句一樣工作。

Case() 也適用於 filter() 子句。例如,要查找注冊超過一個月的黃金客戶和注冊超過一年的白金客戶:

>>> a_month_ago = date.today() - timedelta(days=30)
>>> a_year_ago = date.today() - timedelta(days=365)
>>> Client.objects.filter(
...     registered_on__lte=Case(
...         When(account_type=Client.GOLD, then=a_month_ago),
...         When(account_type=Client.PLATINUM, then=a_year_ago),
...     ),
... ).values_list('name', 'account_type')
<QuerySet [('Jack Black', 'P')]>

相關用法


注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.db.models.expressions.Case。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。