这个问题随机开始出现在我身上。我知道 Django 会生成自己的 ID,但我的很多代码一直在使用一直有效的自定义 AutoFields。我今天添加了一个新类并尝试进行迁移,但此错误一直出现。
我确实删除了 AutoFields 的所有实例并重试迁移,但问题仍然存在,这让我相信这是另外一回事......我认为我的 Django 版本根本没有改变......
错误:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
338, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line
330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 390,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 441,
in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\commands\makemigrat
ions.py", line 98, in handle
loader.project_state(),
File "C:\Python34\lib\site-packages\django\db\migrations\loader.py", line 326,
in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self
.unmigrated_apps))
File "C:\Python34\lib\site-packages\django\db\migrations\graph.py", line 231,
in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Python34\lib\site-packages\django\db\migrations\migration.py", line 8
3, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Python34\lib\site-packages\django\db\migrations\operations\fields.py"
, line 51, in state_forwards
state.reload_model(app_label, self.model_name_lower)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 152,
in reload_model
self.apps.render_multiple(states_to_be_rendered)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 262,
in render_multiple
model.render(self)
File "C:\Python34\lib\site-packages\django\db\migrations\state.py", line 546,
in render
body,
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 189, in __
new__
new_class.add_to_class(obj_name, obj)
File "C:\Python34\lib\site-packages\django\db\models\base.py", line 324, in ad
d_to_class
value.contribute_to_class(cls, name)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line
989, in contribute_to_class
"A model can't have more than one AutoField."
AssertionError: A model can't have more than one AutoField.
这是我的领域之一的示例:
assetid = models.AutoField(primary_key=True)
我的很多代码已经依赖于名称本身,因此更改名称将是一个大问题。此外,这之前工作得很好!我现在似乎无法迁移它。我应该提到我使用的是 sqlite3 数据库。
请您参考如下方法:
这是因为 Django 默认使用 AutoField 作为 id.....所以,如果您希望其他字段为 AutoField,请确保确认 primary_key=True。 这样做会从数据库中删除 id 字段。
我使用 Mysql 作为我的数据库。确保此问题在其他数据库中可能无法解决。
