Skip to content

Instantly share code, notes, and snippets.

@dnozay
Created January 8, 2015 18:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnozay/0a98d4028ecf53f1481c to your computer and use it in GitHub Desktop.
Save dnozay/0a98d4028ecf53f1481c to your computer and use it in GitHub Desktop.
django custom unique_together constraint name.
# named_indices/models.py
from django.db.backends.schema import BaseDatabaseSchemaEditor
old_create_index_name = BaseDatabaseSchemaEditor._create_index_name
if not hasattr(BaseDatabaseSchemaEditor, '_old_create_index_name'):
setattr(BaseDatabaseSchemaEditor, '_old_create_index_name', old_create_index_name)
def _create_index_name(self, model, column_names, suffix=""):
try:
return model._meta._index_names[column_names]
except (KeyError, AttributeError, TypeError):
# KeyError - index name not defined for tuple
# AttributeError - _index_names not defined on model._meta
# TypeError - not using hashable key (e.g. list instead of tuple)
return self._old_create_index_name(model, column_names, suffix)
setattr(BaseDatabaseSchemaEditor, '_create_index_name', _create_index_name)
INSTALLED_APPS += ('named_indices',)
# testapp/models.py
from django.db import models
class MyModel(models.Model):
clid = models.AutoField(primary_key=True, db_column='CLID')
csid = models.IntegerField(db_column='CSID')
cid = models.IntegerField(db_column='CID')
uuid = models.CharField(max_length=96, db_column='UUID', blank=True)
class Meta:
unique_together = [
("csid", "cid", "uuid"),
]
_index_names = {
("csid", "cid", "uuid"): 'custom_index_name',
}
@mullerivan
Copy link

Cool hack, thanks for it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment