本文介紹 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()))
相關用法
- Python Django ContentTypeManager用法及代碼示例
- Python Condition release()用法及代碼示例
- Python Collections.UserString用法及代碼示例
- Python Condition notify()用法及代碼示例
- Python Django ContextMixin.get_context_data用法及代碼示例
- Python Condition wait()用法及代碼示例
- Python Django Cot用法及代碼示例
- Python Collections.UserDict用法及代碼示例
- Python Django CoordTransform用法及代碼示例
- Python Collections.UserList用法及代碼示例
- Python Condition acquire()用法及代碼示例
- Python Django ContentFile用法及代碼示例
- Python Django Collate用法及代碼示例
- Python Condition notify_all()用法及代碼示例
- Python Django ComboField.fields用法及代碼示例
- Python Django Concat用法及代碼示例
- Python Django Cos用法及代碼示例
- Python Django ContextMixin.extra_context用法及代碼示例
- Python Tableau CSVRequestOptions用法及代碼示例
- Python Calendar itermonthdays2()用法及代碼示例
- Python Calendar monthdatescalendar()用法及代碼示例
- Python CSV轉JSON用法及代碼示例
- Python Django CustomUserManager.create_user用法及代碼示例
- Python Calendar itermonthdates()用法及代碼示例
- Python Calendar iterweekdays()用法及代碼示例
注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.db.models.functions.Coalesce。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。