Suppose I have a field f in my model defined as follows as a foreign key:
f = models.ForeignKey(AnotherModel)
When Django syncs database, the filed created in db will be called f_id
, automatically suffixed with '_id'.
The problem is I want this field in db named exactly as what I defined in model, f
in this case. How can I achieve that?
You'll always deal with the field names of your model object. So you could say that Django will construct a "twin" column, with an _id suffix. This column has the same type as the type of the primary key of the model you target, and that column will thus contain the primary key of the model object you use.
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.
Your intermediate model must contain one - and only one - foreign key to the target model (this would be Person in our example). If you have more than one foreign key, a validation error will be raised.
The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.
Well it turns out there's a keyword argument called db_column
. If you want the field called 'f' in the database is just as simple as:
f = models.ForeignKey(AnotherModel, db_column='f')
Further reference:
The name of the database column to use for this field. If this isn't given, Django will use the field's name.
If your database column name is an SQL reserved word, or contains characters that aren't allowed in Python variable names -- notably, the hyphen -- that's OK. Django quotes column and table names behind the scenes.
https://docs.djangoproject.com/en/2.2/ref/models/fields/#db-column
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