[Fixed]-Django 1.9: constrain model fields such that both cannot be 'True'

0👍

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)

1👍

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.

👤Soviut

Leave a comment