Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django suffix ForeignKey field with _id

Tags:

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?

like image 765
Simon Liu Avatar asked Oct 29 '12 05:10

Simon Liu


People also ask

What is _ID in Django?

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 does ForeignKey mean in 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.

Can a model have two foreign keys in Django?

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.

What is the difference between ForeignKey and OneToOneField?

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.


1 Answers

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

like image 132
Simon Liu Avatar answered Sep 21 '22 15:09

Simon Liu