Django suffix ForeignKey field with _id

Deadly 提交于 2019-12-20 18:07:30

问题


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:


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



来源:https://stackoverflow.com/questions/13116130/django-suffix-foreignkey-field-with-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!