'Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.'

def get_relations(self, cursor, table_name):

    my_field_dict = self._name_to_index(cursor, table_name)
    constraints = []
    relations = {}
    try:
        cursor.execute('\n                                                                SELECT    column_name,    referenced_table_name,    referenced_column_name\n                                                                FROM    information_schema.key_column_usage\n                                                                WHERE    table_name    =    %s\n                                                                                AND    table_schema    =    DATABASE()\n                                                                                AND    referenced_table_name    IS    NOT    NULL\n                                                                                AND    referenced_column_name    IS    NOT    NULL', [table_name])
        constraints.extend(cursor.fetchall())
    except (ProgrammingError, OperationalError):
        cursor.execute(('SHOW    CREATE    TABLE    %s' % self.connection.ops.quote_name(table_name)))
        for row in cursor.fetchall():
            pos = 0
            while True:
                match = foreign_key_re.search(row[1], pos)
                if (match == None):
                    break
                pos = match.end()
                constraints.append(match.groups())
    for (my_fieldname, other_table, other_field) in constraints:
        other_field_index = self._name_to_index(cursor, other_table)[other_field]
        my_field_index = my_field_dict[my_fieldname]
        relations[my_field_index] = (other_field_index, other_table)
    return relations
