Django模型的限制条件确保一个或两个字段不是空字符串
遵循这个答案我想对Django模型设置约束,该模型确保设置了两个字段中的一个或两个。但是,尽管该答案假设空字段为null
,但在我的情况下,它们总是是空字符串。我不确定如何在约束中检查一下。
from django.db import models
from django.db.models import Q
class Person(models.Model):
firstname = models.CharField(max_length=150, blank=True, null=False, default="")
surname = models.CharField(max_length=150, blank=True, null=False, default="")
class Meta:
constraints = [
models.CheckConstraint(
name="%(app_label)s_%(class)s_firstname_and_or_surname",
check=(
Q(firstname__exact="", surname__exact!="")
| Q(firstname__exact!="", surname__exact="")
| Q(firstname__exact!="", surname__exact!="")
),
)
]
这应该有效,除了surname_isnull = false
,surname__exact!=“”
不是有效语法。
我知道,如果我有一个QuerySet,我可以使用ubled(surname__exact =“”)
表示“不是空”,但是我不确定如何在此约束中使用来做到这一点。 Q()
表达式。
Following this answer I want to set up a constraint on a Django model that ensures one or both of two fields are set. However, while that answer assumes the empty fields are NULL
, in my case they are always empty strings. I'm not sure how to check for that in the constraint.
from django.db import models
from django.db.models import Q
class Person(models.Model):
firstname = models.CharField(max_length=150, blank=True, null=False, default="")
surname = models.CharField(max_length=150, blank=True, null=False, default="")
class Meta:
constraints = [
models.CheckConstraint(
name="%(app_label)s_%(class)s_firstname_and_or_surname",
check=(
Q(firstname__exact="", surname__exact!="")
| Q(firstname__exact!="", surname__exact="")
| Q(firstname__exact!="", surname__exact!="")
),
)
]
This should work except that, unlike surname_isnull=False
, surname__exact!=""
isn't valid syntax.
I know that if I had a queryset I could use exclude(surname__exact="")
to mean "is not empty", but I'm not sure how to do that in this constraint with Q()
expressions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
〜
用作不是
操作员:You can use
~
as theNOT
operator: