问题
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