Code

Ticket #15076: 15194-3.diff

File 15194-3.diff, 2.3 KB (added by claudep, 2 years ago)

Identical patch + updated test

Line 
1diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py
2index 8da0d7e..af2da45 100644
3--- a/django/core/management/commands/inspectdb.py
4+++ b/django/core/management/commands/inspectdb.py
5@@ -41,8 +41,10 @@ class Command(NoArgsCommand):
6         yield ''
7         yield 'from %s import models' % self.db_module
8         yield ''
9+        known_models = []
10         for table_name in connection.introspection.get_table_list(cursor):
11             yield 'class %s(models.Model):' % table2model(table_name)
12+            known_models.append(table2model(table_name))
13             try:
14                 relations = connection.introspection.get_relations(cursor, table_name)
15             except NotImplementedError:
16@@ -83,7 +85,12 @@ class Command(NoArgsCommand):
17 
18                 if i in relations:
19                     rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
20-                    field_type = 'ForeignKey(%s' % rel_to
21+
22+                    if rel_to in known_models:
23+                        field_type = 'ForeignKey(%s' % rel_to
24+                    else:
25+                        field_type = "ForeignKey('%s'" % rel_to
26+
27                     if att_name.endswith('_id'):
28                         att_name = att_name[:-3]
29                     else:
30diff --git a/tests/regressiontests/inspectdb/tests.py b/tests/regressiontests/inspectdb/tests.py
31index 944eb64..6896bf9 100644
32--- a/tests/regressiontests/inspectdb/tests.py
33+++ b/tests/regressiontests/inspectdb/tests.py
34@@ -12,7 +12,8 @@ class InspectDBTestCase(TestCase):
35         call_command('inspectdb', stdout=out)
36         error_message = "inspectdb generated an attribute name which is a python keyword"
37         self.assertNotIn("from = models.ForeignKey(InspectdbPeople)", out.getvalue(), msg=error_message)
38-        self.assertIn("from_field = models.ForeignKey(InspectdbPeople)", out.getvalue())
39+        # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
40+        self.assertIn("from_field = models.ForeignKey('InspectdbPeople')", out.getvalue())
41         self.assertIn("people_pk = models.ForeignKey(InspectdbPeople, primary_key=True)",
42             out.getvalue())
43         self.assertIn("people_unique = models.ForeignKey(InspectdbPeople, unique=True)",