首页 > 解决方案 > 姜戈。创建复合主键

问题描述

我想创建像 {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)的问题?

标签: pythondjangopostgresqldjango-models

解决方案


推荐阅读