Skip to content

Instantly share code, notes, and snippets.

@dnozay
Created January 9, 2015 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnozay/af509ffb5318c7902960 to your computer and use it in GitHub Desktop.
Save dnozay/af509ffb5318c7902960 to your computer and use it in GitHub Desktop.
django 1.6, add unique_together constraint name.
class CustomDatabaseCreation(BaseDatabaseCreation):
def sql_create_model(self, model, style, known_models=set()):
final_output, pending_references = super(CustomDatabaseCreation, self).sql_create_model(model, style, known_models)
# get output generated by parent class for unique_together.
for field_constraints in opts.unique_together:
line = (' ' + style.SQL_KEYWORD('UNIQUE') + ' (%s)' %
", ".join(
[style.SQL_FIELD(qn(opts.get_field(f).column))
for f in field_constraints]))
try:
constraint_name = model._meta._index_names[field_constraints]
replacement_line = (' CONSTRAINT %s ' % constraint_name
+ style.SQL_KEYWORD('UNIQUE') + ' (%s)' %
", ".join(
[style.SQL_FIELD(qn(opts.get_field(f).column))
for f in field_constraints]))
# add the name in...
final_output = final_output.replace(line, replacement_line)
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)
continue
return final_output, pending_references
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment