Django Model - choices versus foreign key?

Viewed 4955

I understand that in Django, the ORM doesn't support the ENUM type in MySQL or PostgreSQL, as this was originally a MySQL extension, and not portable across other DB types. So the two options are to use a "choices" argument to your model, or using a foreign key reference.

What are the pros and cons of these approaches?

For something like gender, I assume you would use "choices", e.g.:

GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
...
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

However, for something like state names, what are the reason for and against using a separate table, and foreign keys to that table?

state = models.ForeignKey(AustralianState)

Under what circumstances would you use one versus the other?

Cheers, Victor

3 Answers

I would recommend using lookup tables by default, otherwise you are maintaining data in your code. It also makes the lookup values accessible to users that access the database directly, not via your application (e.g. BI/reporting functions).

A notable exception - where I would use choices instead of a lookup table - is a lookup entity that has values that control code-level logic. You often find this with "status" or "type" entities (e.g. BillingType), where the logic depends on the value of the "type" field. In these cases, the code usually refers to explicit identifiers (codes) of those types, and the addition of a new type would require logic changes (in code) in any case.

Related