[Answered ]-"django.db.utils.ProgrammingError: relation already exists" for unique together constraint

1👍

Please don’t alter the databae manually. If you later migrate another database, it will produce the same problems. The idea of migrations is to create a database, without having to interact with the database manually.

A problem is that Django does not have a DeleteUniqueTogether, but only a AlterUniqueTogether [Django-doc] and likely this will not change in the near future: unique_together should not be used anymore. Django has a constraint framework [Django-doc].

Your MyTable thus should use:

class MyTable(models.Model):
    # ...

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=('myfield1', 'myfield2'),
                name='mytable_myfield1_myfield2_cb8c1059_uniq'
            )
        ]

If there is a specific reason why that is not possible, you should let the migration run the query:

class Migration(migrations.Migration):

    dependencies = [
        ('api', '...'),
    ]

    operations = [
        migrations.RunSQL(
            'ALTER TABLE mytable DROP CONSTRAINT mytable_myfield1_myfield2_cb8c1059_uniq;'
        ),
        migrations.AlterUniqueTogether(
            name='mytable',
            unique_together={('myfield', 'myfield2')},
        ),
    ]

0👍

You can list the constraints on the table opening a Postgres shell and doing \d mytable. Once you have found the name of the constraint, you can delete it with something like:

ALTER TABLE mytable DROP CONSTRAINT mytable_myfield1_myfield2_cb8c1059_uniq;

Leave a comment