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


Python Django Coalesce用法及代碼示例


本文介紹 django.db.models.functions.Coalesce 的用法。

聲明

class Coalesce(*expressions, **extra)

接受至少兩個字段名稱或表達式的列表並返回第一個非空值(請注意,空字符串不被視為空值)。每個參數必須是相似的類型,因此混合文本和數字將導致數據庫錯誤。

使用示例:

>>> # Get a screen name from least to most public
>>> from django.db.models import Sum
>>> from django.db.models.functions import Coalesce
>>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
>>> author = Author.objects.annotate(
...    screen_name=Coalesce('alias', 'goes_by', 'name')).get()
>>> print(author.screen_name)
Maggie

>>> # Prevent an aggregate Sum() from returning None
>>> # The aggregate default argument uses Coalesce() under the hood.
>>> aggregated = Author.objects.aggregate(
...    combined_age=Sum('age'),
...    combined_age_default=Sum('age', default=0),
...    combined_age_coalesce=Coalesce(Sum('age'), 0),
... )
>>> print(aggregated['combined_age'])
None
>>> print(aggregated['combined_age_default'])
0
>>> print(aggregated['combined_age_coalesce'])
0

警告

傳遞給 MySQL 上的 Coalesce 的 Python 值可能會轉換為不正確的類型,除非顯式轉換為正確的數據庫類型:

>>> from django.db.models import DateTimeField
>>> from django.db.models.functions import Cast, Coalesce
>>> from django.utils import timezone
>>> now = timezone.now()
>>> Coalesce('updated', Cast(now, DateTimeField()))

相關用法


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