Nepo Znat
Nepo Znat

Reputation: 3300

Django model choice field naming convention

What is the naming convention for the names of a choice field.

class Student(models.Model):
    ACTIVE= 'active'
    INACTIVE= 'inactive'
    NOT_AVAILABLE= 'not-available'
    STATUS_CHOICES = (
        (ACTIVE, 'Active'),
        (INACTIVE, 'Inactive'),
        (NOT_AVAILABLE, 'Not available'),
    )
    status = models.CharField(
        max_length=15,
        choices=STATUS_CHOICES ,
        default=INACTIVE,
    )

What naming convention should I choose for the NOT_AVAILABLE field?

not-available or not_available

Upvotes: 1

Views: 862

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

There is nothing magical about these choices. The left tuple items (let us call these the keys) are stored in the database, and the right tuple items (let us call these the values) are the displays of these values (so a more human readable value).

The idea is that the values can be culture-variant (for example depending on the language get translated), whereas the keys are invariant: regardless of the settings, the keys are typically always the same. Since these are stored in the database, these do not have to be pretty, since the programmer should be able to understand what they mean. If one would however translate keys as well, then this could imply that after changing the language of a server, Django can no longer interpret the rows that contain items in the old translation. Since 'active' is of course not equal to 'actief' (Dutch translation).

My personal advice is to use the underscore here, since then it is a Python identifier as well, so you could then later use it for a getattr(..) operation. For example:

getattr(Student, some_student.status.upper())

could then be used to obtain STUDENT.NOT_AVAILABLE in case some_student has as status the 'not_available' string, but as said before, there can be both reasons for the former, and the latter approach.

Upvotes: 1

Related Questions