Created
January 8, 2015 18:49
-
-
Save dnozay/0a98d4028ecf53f1481c to your computer and use it in GitHub Desktop.
django custom unique_together constraint name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSTALLED_APPS += ('named_indices',) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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', | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool hack, thanks for it