I know Django does not support foreign keys across multiple databases (originally Django 1.3 docs)
But I\'m looking for a workaround.
This solution is originally written for one managed database with migrations and one or more legacy databases with models Meta managed=False
connected at database level to the same database. If a db_table
option contains a database name plus table name quoted correctly by ' ` ' (MySQL) or by ' " ' (other db), e.g. db_table = '"DB2"."table_b"'
, then it is not quoted any more by Django. Queries are compiled by Django ORM correctly, even with JOINs:
class TableB(models.Model):
....
class Meta:
db_table = '`DB2`.`table_b`' # for MySQL
# db_table = '"DB2"."table_b"' # for all other backends
managed = False
Query set:
>>> qs = TableB.objects.all()
>>> str(qs.query)
'SELECT "DB2"."table_b"."id" FROM DB2"."table_b"'
That is supported by all db backends in Django.
(It seems that I started a bounty on a duplicate new question where my answer continues.)