Skip to content

Commit ddc5d59

Browse files
committed
Fixed django#15076 -- Quoted ForeignKey target class names in inspectdb when class is defined below.
Thanks saschwarz for the report, [email protected] for the initial patch and Ramiro Morales for the review. git-svn-id: http://code.djangoproject.com/svn/django/trunk@17942 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent c34d069 commit ddc5d59

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

django/core/management/commands/inspectdb.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,10 @@ def handle_inspection(self, options):
4141
yield ''
4242
yield 'from %s import models' % self.db_module
4343
yield ''
44+
known_models = []
4445
for table_name in connection.introspection.get_table_list(cursor):
4546
yield 'class %s(models.Model):' % table2model(table_name)
47+
known_models.append(table2model(table_name))
4648
try:
4749
relations = connection.introspection.get_relations(cursor, table_name)
4850
except NotImplementedError:
@@ -83,7 +85,12 @@ def handle_inspection(self, options):
8385

8486
if i in relations:
8587
rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
86-
field_type = 'ForeignKey(%s' % rel_to
88+
89+
if rel_to in known_models:
90+
field_type = 'ForeignKey(%s' % rel_to
91+
else:
92+
field_type = "ForeignKey('%s'" % rel_to
93+
8794
if att_name.endswith('_id'):
8895
att_name = att_name[:-3]
8996
else:

tests/regressiontests/inspectdb/tests.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ def test_attribute_name_not_python_keyword(self):
1212
call_command('inspectdb', stdout=out)
1313
error_message = "inspectdb generated an attribute name which is a python keyword"
1414
self.assertNotIn("from = models.ForeignKey(InspectdbPeople)", out.getvalue(), msg=error_message)
15-
self.assertIn("from_field = models.ForeignKey(InspectdbPeople)", out.getvalue())
15+
# As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
16+
self.assertIn("from_field = models.ForeignKey('InspectdbPeople')", out.getvalue())
1617
self.assertIn("people_pk = models.ForeignKey(InspectdbPeople, primary_key=True)",
1718
out.getvalue())
1819
self.assertIn("people_unique = models.ForeignKey(InspectdbPeople, unique=True)",

0 commit comments

Comments
 (0)