I have a problem with my code. My friend helped me to write some code in JavaScript, but to do that part of code, he had to add a field with the "db_column" option. After he has done that, when i run the tests, i have an error: "duplicate column name: ID". Now my friend can't help me anymore, and i can't find a solution for this...
Here is the models.py:
class Item(models.Model):
name = models.CharField(max_length=50)
type = models.CharField(max_length=50, validators=[RegexValidator('helmet|torso|pants|gauntlets|weapon|accessory')])
bonus = models.ForeignKey(Statistics, on_delete=models.CASCADE)
durability = models.IntegerField()
image = models.ImageField(upload_to='DeepDungeon/static/images/items')
itemId = models.IntegerField(db_column='ID')
And here is the error:
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/Users/manuel/Programmazione/PyCharm/DeepDungeon/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute
return self.cursor.execute(sql)
File "/Users/manuel/Programmazione/PyCharm/DeepDungeon/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 421, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: duplicate column name: ID
CodePudding user response:
Behind the scene, django is automatically adding an ID field which is the primary key of the model, so by adding db_column="ID"
on itemId collides with the primary key of the Item model.
You can fix that in 2 ways:
class Item(models.Model):
name = models.CharField(max_length=50)
type = models.CharField(max_length=50, validators=[RegexValidator('helmet|torso|pants|gauntlets|weapon|accessory')])
bonus = models.ForeignKey(Statistics, on_delete=models.CASCADE)
durability = models.IntegerField()
image = models.ImageField(upload_to='DeepDungeon/static/images/items')
# add primary key on the itemId if you know that this always will be unique
itemId = models.IntegerField(db_column='ID', primary_key=True)
# OR, define a new primary key
pk = models.AutoField(primary_key=True)