Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model - choices versus foreign key?

Tags:

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

like image 555
victorhooi Avatar asked Oct 26 '10 06:10

victorhooi


People also ask

How do you add a choice to a foreign key in Django?

The proper way to do it is in three distinct steps/migrations: Create the Category model and add a foreign key to it in the Sample model. You should not remove the existing choices field! So you'll need to add another field to Sample for example named category_fk.

What is a foreign key Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

What is On_delete in Django?

The on_delete method is used to tell Django what to do with model instances that depend on the model instance you delete. (e.g. a ForeignKey relationship). The on_delete=models. CASCADE tells Django to cascade the deleting effect i.e. continue deleting the dependent models as well.

What is Db_column?

The db_column changes the name of the column in the database. It does not change the name of the model attribute used by Django.


2 Answers

I would use choices where the choices wouldn't change over time. If they would, a FK with a new model would be better.

like image 166
Gabi Purcaru Avatar answered Oct 08 '22 03:10

Gabi Purcaru


You should also consider foreign keys when the number of potential choices is large. That's one of the reasons to consider using FK for countries or states. Otherwise, you're effectively hard-coding a lot of data in your source code.

like image 38
Jordan Reiter Avatar answered Oct 08 '22 03:10

Jordan Reiter