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
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 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.
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.
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.
I would use choices where the choices wouldn't change over time. If they would, a FK with a new model would be better.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With