S. Liu
S. Liu

Reputation: 1078

Django suffix ForeignKey field with _id

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?

Upvotes: 31

Views: 21079

Answers (1)

S. Liu
S. Liu

Reputation: 1078

Well it turns out there's a keyword argument called db_column. If you want the field named 'f' in the database table, it's 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

Upvotes: 39

Related Questions