allo allo - 1 month ago 14
MySQL Question

Django unique_together creates an index without UNIQUE constraint

I have a model:

class MyModel(models.Model)
class Meta:
unique_together=["a", "b"]
index_together=["a", "b"]
a=models.IntegerField(null=True, blank=True)
b=models.ForeignKey("othermodel")


Migrations for this model:

class Migration(migrations.Migration):
dependencies = [
('app', 'previous_migration'),
]
operations = [
migrations.AlterUniqueTogether(
name='mymodel',
unique_together=set([('a', 'b')]),
),
migrations.AlterIndexTogether(
name='mymodel',
index_together=set([('a', 'b')]),
),
]


./manage.py sqlmigrate app mymigration


BEGIN;
CREATE INDEX `app_mymodel_id_asdfasfd_idx` ON `app_mymodel` (`a`, `b`);

COMMIT;


And i am using a MySQL database.

Django (1.8.5) now creates an index over both fields together, but with type
INDEX
and not type
UNIQUE
, which does not result in the expected
IntegrityError
when saving a duplicate. Manually changing the index results in the correct behaviour.

With just the
AlterUniqueTogether
migration, i get an empty output for
/manage.py sqlmigrate
.

How do i tell Django to create an
UNIQUE
index? Or is there a good reason why the created index is not setup this way?

Answer

With django 1.8 and a fresh installation with syncdb of the app, all needed indexes are created. I currently cannot reproduce the issue, as the old installation has the index manually created and fresh installations create it with syncdb and with migrate without any problems.

I did not test more recent django yet, but i assume it works as well.

Comments