Anonymous avatar Anonymous committed 3b23a7a

Fixed #15076 -- Quoted ForeignKey target class names in inspectdb when class is defined below.

Thanks saschwarz for the report, for the initial patch and Ramiro Morales for the review.

Comments (0)

Files changed (2)


         yield ''
         yield 'from %s import models' % self.db_module
         yield ''
+        known_models = []
         for table_name in connection.introspection.get_table_list(cursor):
             yield 'class %s(models.Model):' % table2model(table_name)
+            known_models.append(table2model(table_name))
                 relations = connection.introspection.get_relations(cursor, table_name)
             except NotImplementedError:
                 if i in relations:
                     rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1])
-                    field_type = 'ForeignKey(%s' % rel_to
+                    if rel_to in known_models:
+                        field_type = 'ForeignKey(%s' % rel_to
+                    else:
+                        field_type = "ForeignKey('%s'" % rel_to
                     if att_name.endswith('_id'):
                         att_name = att_name[:-3]


         call_command('inspectdb', stdout=out)
         error_message = "inspectdb generated an attribute name which is a python keyword"
         self.assertNotIn("from = models.ForeignKey(InspectdbPeople)", out.getvalue(), msg=error_message)
-        self.assertIn("from_field = models.ForeignKey(InspectdbPeople)", out.getvalue())
+        # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
+        self.assertIn("from_field = models.ForeignKey('InspectdbPeople')", out.getvalue())
         self.assertIn("people_pk = models.ForeignKey(InspectdbPeople, primary_key=True)",
         self.assertIn("people_unique = models.ForeignKey(InspectdbPeople, unique=True)",
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.