Django模型的限制条件确保一个或两个字段不是空字符串

发布于 2025-02-09 11:54:17 字数 1137 浏览 2 评论 0原文

遵循这个答案我想对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 = falsesurname__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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尽揽少女心 2025-02-16 11:54:17

您可以将用作 不是操作员

check = (
    Q(Q(firstname__exact="") & ~Q(surname__exact="")) | 
    Q(~Q(firstname__exact="") & Q(surname__exact="")) | 
    Q(~Q(firstname__exact="") & ~Q(surname__exact=""))
)

You can use ~ as the NOT operator:

check = (
    Q(Q(firstname__exact="") & ~Q(surname__exact="")) | 
    Q(~Q(firstname__exact="") & Q(surname__exact="")) | 
    Q(~Q(firstname__exact="") & ~Q(surname__exact=""))
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文