Choices in Django

Whenever you have a multiple choices in Django, make it custom to define them in CONSTANTS in choices.py
This way, you keep your code DRY and make comparisons more readable.

choices.py

from django.utils.translation import ugettext_lazy as _

STATUS_BEING_BUILT = 1
STATUS_BUILD = 2
STATUS_BUILD_FAILED = 3

STATUS_CHOICES = (
    (STATUS_BEING_BUILT, _('Being built')),
    (STATUS_BUILD, _('Build')),
    (STATUS_BUILD_FAILED, _('Failed to build')),
)

 

This is more readable and maintainable:

assert object.status == STATUS_BEING_BUILT

Than this:

assert object.status == 1

 

Now to easily get the label of a choice you can do this:

dict(STATUS_CHOICES)[STATUS_BEING_BUILT]

To check wether a choice is a valid choice:

def is_valid_choice(value):
    return value in dict(STATUS_CHOICES)