﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
9779	Adding Foreign Key detection to SQLite inspectdb	gabbott	nobody	"I was using the SQLite introspection and realized that it didn't support foreign key detection. I realize that SQLite does not enforce the ""reference"" sqlite commands the data is there and can easily be parsed out. Here is my patch:

{{{
Index: django/db/backends/sqlite3/introspection.py
===================================================================
--- django/db/backends/sqlite3/introspection.py	(revision 9627)
+++ django/db/backends/sqlite3/introspection.py	(working copy)
@@ -55,8 +55,59 @@
                  info['null_ok']) for info in self._table_info(cursor, table_name)]
 
     def get_relations(self, cursor, table_name):
-        raise NotImplementedError
+        """"""
+        Returns a dictionary of {field_index: (field_index_other_table, other_table)}
+        representing all relationships to the given table. Indexes are 0-based.
+        """"""
+        
+        import re
+        
+        # Dictionary of relations to return
+        relations = {}
+        
+        # Schema for this table
+        cursor.execute(""select sql from sqlite_master where tbl_name='%s'"" % table_name)
+        results = cursor.fetchone()[0].strip()
+        results = results.split('(', 1)[1]
+        results = results.rsplit(')', 1)[0]
 
+        # walk through and look for references to other tables.
+        for index, i in enumerate(results.split(',')):
+            i = i.strip()
+            if i.startswith(""UNIQUE""):
+                continue
+
+            m = re.search('references (.*) \([""|](.*)[""|]\)', i, re.I)
+            
+            if not m:
+                continue
+        
+            table, column = m.groups()
+            
+            table = table.strip('""')
+            column = column.strip('""')
+            
+            cursor.execute(""select sql from sqlite_master where tbl_name='%s'"" % table)
+            
+            other_table_results = cursor.fetchone()[0].strip()
+            other_table_results = other_table_results.split('(', 1)[1]
+            other_table_results = other_table_results.rsplit(')', 1)[0]
+            
+            second_index = None
+            for _index, j in enumerate(other_table_results.split(',')):
+                j = j.strip()
+                if j.startswith('UNIQUE'):
+                    continue
+
+                name = j.split(' ', 1)[0].strip('""')
+                if name == column:
+                    second_index = _index
+            
+            if second_index != None:
+                relations[index] = (second_index, table)
+                            
+        return relations
+
     def get_indexes(self, cursor, table_name):
         """"""
         Returns a dictionary of fieldname -> infodict for the given table,
}}}"		closed	django-admin.py inspectdb	dev		fixed		Ramiro Morales	Accepted	1	0	0	0	0	0
