Brian Witte
Brian Witte

Reputation: 53

Django 1.9: constrain model fields such that both cannot be 'True'

How can I constrain this model such that bar and baz cannot both be True?

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

Edit: The properties in the fields serve different, but related, purposes. The question arises from working with a large project where replacing bar and baz with a single choice field would require a major rewrite.

Upvotes: 0

Views: 42

Answers (2)

Aaron Lelevier
Aaron Lelevier

Reputation: 20820

You can super override the save method to enforce logic:

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)

Upvotes: 0

Soviut
Soviut

Reputation: 91585

This would be better suited to a single field with choices. Examples of this are clothing sizes, genders, subscription levels, etc.

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')

You can then compare them in your views:

foo = Foo.objects.get(id=1)
if foo.size == Foo.SMALL:
    print 'this foo is small'

This is a common pattern in Django and can represent the choices in forms using ChoiceFields and ModelChoiceFields. They're also well supported in the Django Admin app and ModelForms. These form fields can be rendered using either the dropdown select widget or radio buttons widget.

Upvotes: 1

Related Questions