运行 在 Django 中进行测试时出现重复的列名

Duplicate column name when running tests in Django

我的代码有问题。 我的朋友帮我在JavaScript中写了一些代码,但是要完成那部分代码,他必须添加一个带有“db_column”选项的字段。 在他完成之后,当我 运行 测试时,出现错误:“重复的列名:ID”。 现在我的朋友帮不了我了,我也找不到解决办法...

这里是 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')

这里是错误:

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

在后台,django 会自动添加一个 ID 字段,它是模型的主键,因此在 itemId 上添加 db_column="ID" 会与 Item 模型的主键发生冲突。 您可以通过两种方式解决该问题:

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)