Ticket #2720: constraints.diff
File constraints.diff, 3.3 KB (added by , 18 years ago) |
---|
-
management.py
145 145 opts = model._meta 146 146 final_output = [] 147 147 table_output = [] 148 references = [] 148 149 pending_references = {} 149 150 for f in opts.fields: 150 151 if isinstance(f, models.ForeignKey): … … 165 166 field_output.append(style.SQL_KEYWORD('PRIMARY KEY')) 166 167 if f.rel: 167 168 if f.rel.to in known_models: 168 field_output.append(style.SQL_KEYWORD('REFERENCES') + ' ' + \169 reference = style.SQL_KEYWORD('REFERENCES') + ' ' + \ 169 170 style.SQL_TABLE(backend.quote_name(f.rel.to._meta.db_table)) + ' (' + \ 170 171 style.SQL_FIELD(backend.quote_name(f.rel.to._meta.get_field(f.rel.field_name).column)) + ')' 171 ) 172 field_output.append(reference) 173 references.append('FOREIGN KEY (%s) ' % style.SQL_FIELD(backend.quote_name(f.column)) + reference) 172 174 else: 173 175 # We haven't yet created the table to which this field 174 176 # is related, so save it for later. … … 181 183 for field_constraints in opts.unique_together: 182 184 table_output.append(style.SQL_KEYWORD('UNIQUE') + ' (%s)' % \ 183 185 ", ".join([backend.quote_name(style.SQL_FIELD(opts.get_field(f).column)) for f in field_constraints])) 184 186 for constraint in references: 187 table_output.append(style.SQL_KEYWORD('CONSTRAINT') + ' ' + constraint) 185 188 full_statement = [style.SQL_KEYWORD('CREATE TABLE') + ' ' + style.SQL_TABLE(backend.quote_name(opts.db_table)) + ' ('] 186 189 for i, line in enumerate(table_output): # Combine and add commas. 187 190 full_statement.append(' %s%s' % (line, i < len(table_output)-1 and ',' or '')) … … 244 247 style.SQL_KEYWORD('NOT NULL REFERENCES'), 245 248 style.SQL_TABLE(backend.quote_name(f.rel.to._meta.db_table)), 246 249 style.SQL_FIELD(backend.quote_name(f.rel.to._meta.pk.column)))) 247 table_output.append(' %s (%s, %s) ' % \250 table_output.append(' %s (%s, %s),' % \ 248 251 (style.SQL_KEYWORD('UNIQUE'), 249 252 style.SQL_FIELD(backend.quote_name(f.m2m_column_name())), 250 253 style.SQL_FIELD(backend.quote_name(f.m2m_reverse_name())))) 254 table_output.append(' %s (%s) %s %s (%s),' % \ 255 (style.SQL_KEYWORD('CONSTRAINT FOREIGN KEY'), 256 style.SQL_FIELD(backend.quote_name(f.m2m_column_name())), 257 style.SQL_KEYWORD('REFERENCES'), 258 style.SQL_TABLE(backend.quote_name(opts.db_table)), 259 style.SQL_FIELD(backend.quote_name(opts.pk.column)))) 260 table_output.append(' %s (%s) %s %s (%s)' % \ 261 (style.SQL_KEYWORD('CONSTRAINT FOREIGN KEY'), 262 style.SQL_FIELD(backend.quote_name(f.m2m_reverse_name())), 263 style.SQL_KEYWORD('REFERENCES'), 264 style.SQL_TABLE(backend.quote_name(f.rel.to._meta.db_table)), 265 style.SQL_FIELD(backend.quote_name(f.rel.to._meta.pk.column)))) 251 266 table_output.append(');') 252 267 final_output.append('\n'.join(table_output)) 253 268 return final_output