我在 Django/PostgreSQL 專案中有一個模型,并希望將以下約束添加到三個可空欄位:要么所有欄位都是 NULL,要么所有欄位都不是.
這是代碼(簡化):
class SomeModel(models.Model):
...
a = models.IntegerField(nullable=True)
b = models.DateTimeField(nullable=True)
c = models.DateTimeField(nullable=True)
...
class Meta:
constraints = [
models.CheckConstraint(
check=(
(Q(a__isnull=True) & Q(b__isnull=True) & Q(c__isnull=True)) |
(Q(a__isnull=False) & Q(b__isnull=False) & Q(c__isnull=False))
)
)
]
如果我理解正確,我剛剛描述了這三個欄位的兩種可能狀態。首先是“所有三個都是 NULL”,其次是“它們都不是 NULL”。
但實際上,我得到的是“它們都不能為 NULL”。Django 管理面板堅持填寫所有欄位,它們都是強制性的。我該如何解決這種行為?謝謝!
uj5u.com熱心網友回復:
這不是由于限制,當您希望允許將表單欄位留空時,您應該指定[Django-doc] ,因此默認為/ :blank=True NoneNULL
class SomeModel(models.Model):
# …
a = models.IntegerField(null=True, blank=True)
b = models.DateTimeField(null=True, blank=True)
c = models.DateTimeField(null=True, blank=True)
class Meta:
constraints = [
models.CheckConstraint(
check=Q(a=None, b=None, c=None) |
Q(a__isnull=False, b__isnull=False, c__isnull=False),
name='all_or_none_null'
)
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451327.html
上一篇:ValueError:具有多個元素的陣列的真值不明確。使用a.any()或a.all()-后跟TypeError
下一篇:顯示資料而不使用回圈Django
