[英]Django: Vacate unique name if field is a particular value
我想要的是
我希望一个字段是唯一的,除非同一 model 中的其他字段是特定值。 允许我将此唯一名称腾出给未来的 model 实例。
我还需要允许testname
为null
给定测试没有testname
。
唯一字段: testname
护发素: cancelled=True
models.py (简体)
class Test(models.Model):
testname = models.CharField(max_length=50, null=True, blank=True, unique=True)
cancelled = models.BooleanField(default=False)
您可以使用UniqueConstraint
:
class Test(models.Model):
testname = models.CharField(max_length=50, null=True, blank=True)
cancelled = models.BooleanField(default=False)
class Meta:
constraints = (
UniqueConstraint(fields=['testname'], condition=Q(cancelled=True), name='...'),
)
这将在您的数据库表中添加一个约束,使该字段具有条件的唯一性。 在这种情况下,不支持开箱即用的表单验证,因此需要单独添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.