Model - Foreign Key db_column Naming Issue

一曲冷凌霜 提交于 2020-01-05 15:17:31

问题


I am having an issue with the db_column parameter in Django. Lets say I have created a model in my models.py:

class Stats(models.Model):
    fk = models.ForeignKey(Game, db_column='fk_gameId')
    score = models.IntegerField(default=0)

and trying to make an insert to the table that is generated from the model, the sample code for the insert operation is like:

 dbQuery = Stats(fk_gameId = requestedGameId,
                 score = gameInfo['score'])

 dbQuery.save()

what happens is that the system throws the following error when executed:

TypeError: 'fk_gameId' is an invalid keyword argument for this function

But if I change the the first parameter of the insert statement like below:

 dbQuery = Stats(fk_id = requestedGameId,
                 score = gameInfo['score'])

 dbQuery.save()

then it works flawlessly although the column name in the DB is "fk_gameId" as I defined it in the model.

Is it normal or am I missing something. Can you help me to understand what is the issue here? Thank you.


回答1:


The db_column changes the name of the column in the database. It does not change the name of the model attribute used by Django.

Since you've defined the field as fk = models.ForeignKey(...), the name of the field in Django is still fk, and the raw id field is named fk_id.



来源:https://stackoverflow.com/questions/34021823/model-foreign-key-db-column-naming-issue

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