0

I want create composite promary key like {id, project_id}. I remove old tables(all). when i do:

python manage.py makemigrations

I have a mistake:

AssertionError: Model mdm.Group can't have more than one AutoField.

change my model:

id = models.AutoField(db_index=True, primary_key=False)

and add composite primary key as

constraints = [
        models.UniqueConstraint(
            fields=['id', 'project_id'], name='unique_group_project'
        )
    ]

From docs:

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).

I just don't understand the problem. If I add AutoField, It's necessarily must PK. How I can resolve problem with Autofield id and composite PK (id, project_id)?

Rustam Pulatov
  • 625
  • 1
  • 9
  • 20
  • From what I remember Django doesn't support composite PKs. If there is a hack to get around it, I think you'll run into issues if you try to use Django's other built-in functionality. This may be useful - https://stackoverflow.com/questions/28712848/composite-primary-key-in-django – ravioli Sep 22 '19 at 06:29
  • Thank you. I saw this topic. Problem is AutoField must been PK. I want set id in AutoField and don't stand PK. – Rustam Pulatov Sep 22 '19 at 06:38

0 Answers0