python - 姜戈。创建复合主键
问题描述
我想创建像 {id, project_id} 这样的复合主键。我删除了旧表(全部)。当我做:
python manage.py makemigrations
我有一个错误:
AssertionError: Model mdm.Group can't have more than one AutoField.
改变我的模型:
id = models.AutoField(db_index=True, primary_key=False)
并将复合主键添加为
constraints = [
models.UniqueConstraint(
fields=['id', 'project_id'], name='unique_group_project'
)
]
来自文档:
By default, Django gives each model the following field:
id = models.AutoField(primary_key=True)
This is an auto-incrementing primary key.
If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column.
Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added).
我只是不明白这个问题。如果我添加AutoField,它一定是必须PK的。如何解决 Autofield id 和复合 PK(id、project_id)的问题?
解决方案
推荐阅读
- c# - 更新在 BackgroundWorker 上运行的 AES 加密/解密的进度条
- java - 缺少类“com.intellij.remoteServer.util.CloudBundle”
- javascript - 如何从 package.json 中参数化环境变量
- javascript - 使用 xhr 简单的 POST 操作时出现 404 NOT FOUND 错误
- c# - 如何在 windows 窗体 c# 中更改按钮名称
- pygame - pygame中奇怪的碰撞行为
- java - 缺少方法 org.apache.commons.io.FileUtils.forceMkdirParent?
- javascript - 在反应js中需要任何一个字段验证
- javascript - 如何使用 show(), hide() & off() 隐藏 div 元素?
- matlab - matlab中的数据导入和计算