Django 1.9:约束模型字段,使得两者都不能是真正的'

时间:2016-10-13 23:15:33

标签: django django-models

如何约束此模型,barbaz不能同时为True

class Foo(models.Model):
    bar = models.BooleanField(default=False)
    baz = models.BooleanField(default=False)

编辑:字段中的属性用于不同但相关的目的。问题来自于一个大型项目,用一个选择字段替换bar和baz需要重大改写。

2 个答案:

答案 0 :(得分:1)

这更适合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中的常见模式,可以使用ChoiceFieldsModelChoiceFields表示表单中的选项。他们在Django Admin应用程序和ModelForms中得到了很好的支持。可以使用下拉选择小部件或单选按钮小部件来呈现这些表单字段。

答案 1 :(得分:0)

您可以'modules_templates' => [ 'driver' => 'local', 'root' => storage_path().'/modules_templates', 覆盖super方法来强制执行逻辑:

save