Code

Ticket #15076: django-fk-quoting.diff

File django-fk-quoting.diff, 1.3 KB (added by jeff@…, 3 years ago)

Quote ForeignKey models only if the model has not appeared yet.

Line 
1diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py
2index e45f22c..2db7a85 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@@ -77,7 +79,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: