我如何约束这个模型,使bar
和baz
不能同时是True
?
class Foo(models.Model):
bar = models.BooleanField(default=False)
baz = models.BooleanField(default=False)
编辑:字段中的属性服务于不同但相关的目的。这个问题出现在一个大型项目中,在这个项目中,用单个选择字段替换bar和baz需要进行大量的重写。
这将更适合choices
的单个字段。例如服装尺寸、性别、订阅级别等。
class Foo(models.Model):
# store the different choices as properties for comparison later
SMALL = 'small'
BIG = 'big'
# group the choices into a list of tuples
# the first value of the tuple is how they're stored in the database
# the second value is how they're displayed to the user
SIZES = (
(SMALL, 'Small'),
(BIG, 'Big'),
)
# apply the choices to the field with a default
size = model.CharField(max_length=10, choices=SIZES, default='small')
你可以在你的视图中比较它们:
foo = Foo.objects.get(id=1)
if foo.size == Foo.SMALL:
print 'this foo is small'
这是Django中的一个常见模式,可以用ChoiceFields
和ModelChoiceFields
来表示表单中的选项。它们在Django Admin应用和ModelForms
中也得到了很好的支持。这些表单字段可以使用下拉选择小部件或单选按钮小部件来呈现。
您可以super
覆盖save
方法来强制执行逻辑:
class Foo(models.Model):
bar = models.BooleanField(default=False)
baz = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if self.bar and self.baz:
raise SomeException()
return super(Foo, self).save(*args, **kwargs)