gpt4 book ai didi

python - 在django模型定义中要求两个字段之一的具体方式

转载 作者:太空狗 更新时间:2023-10-30 02:38:41 24 4
gpt4 key购买 nike

我的模型 MyModel 带有字段 field1field2。我想要求这两个字段之一。我怎样才能做到这一点?

class MyModel(models.Model):
field1 = models.TextField(?)
field2 = models.TextField(?)

我正在寻找一种我见过但忘记的特定的最佳实践方法,而不是重写的 clean 函数方法。我确实记得重写某些函数的方法,但我不认为它是clean

提前致谢

最佳答案

这是一个老问题,但由于这是我搜索“django model field require one of the two”时的第一个问题,我应该指出,虽然重写 clean() 可能3 年前,Django 对 Meta 类中的数据库约束定义的支持是一个很好的实践,现在是一个更好的选择。 This tutorial让我走上正确的道路,但这是我们模型中的代码示例:

class MyModel:

thing1 = models.PositiveIntegerField(null=True)
thing2 = models.PositiveIntegerField(null=True)

class Meta:
constraints = [
models.CheckConstraint(
name="%(app_label)s_%(class)s_thing1_or_thing2",
check=(
models.Q(thing1__isnull=True, thing2__isnull=False)
| models.Q(thing1__isnull=False, thing2__isnull=True)
),
)
]

关于python - 在django模型定义中要求两个字段之一的具体方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com