我有MyModel领域field1和模型field2。我想要这两个字段之一。我怎样才能做到这一点?
class MyModel(models.Model):
field1 = models.TextField(?)
field2 = models.TextField(?)
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种我已看到但被遗忘的特定,最佳实践的方法,而不是最重要的clean函数方法。我确实记得该方法覆盖了某些功能,但是我认为它不是clean。
提前致谢
这是一个老问题,但由于这是我搜索“django 模型字段需要两个中的一个”时的第一次命中,我应该指出,虽然clean()3 年前覆盖可能是一个好习惯,但 Django 对数据库的支持如今,Meta类中的约束定义是更好的选择。 本教程让我走上了正确的道路,但这里有一个来自我们模型的代码示例:
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)
),
)
]
Run Code Online (Sandbox Code Playgroud)
如评论使用干净
class MyModel(models.Model):
field1 = models.TextField(blank=True)
field2 = models.TextField(blank=True)
def clean(self):
if not self.field1 and not self.field2: # This will check for None or Empty
raise ValidationError({'field1': _('Even one of field1 or field2 should have a value.')})
Run Code Online (Sandbox Code Playgroud)