带有_id的Django后缀ForeignKey字段 [英] Django suffix ForeignKey field with _id
问题描述
f = models.ForeignKey( AnotherModel)
当Django同步数据库时,在db中创建的字段将被称为 f_id
,自动加后缀'_id'。
问题是我想要在db中的这个字段完全像我在模型中定义的 f
在这种情况下。我怎样才能做到这一点?
那么事实证明有一个关键字参数叫做 db_column
。如果你想在数据库中调用'f'字段就像下面这样简单:
f = models.ForeignKey(AnotherModel, db_column ='f')
进一步参考:
用于
此字段的数据库列的名称。如果没有给出,Django将使用该字段的名称。
如果您的数据库列名是一个SQL保留字,或者包含
个字符, t允许在Python变量名称 - 特别是,
连字符 - 没关系。 Django在
幕后引用列名和表名。
https://docs.djangoproject.com/zh/dev/ref/models/fields/#db-column < a>
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?
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
这篇关于带有_id的Django后缀ForeignKey字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!