Django suffix ForeignKey field with _id

2019-03-19 06:02发布

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?

1条回答
我想做一个坏孩纸
2楼-- · 2019-03-19 06:50

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/dev/ref/models/fields/#db-column

查看更多
登录 后发表回答