How to work around lack of support for foreign keys across databases in Django

后端 未结 9 1384
生来不讨喜
生来不讨喜 2020-12-07 09:59

I know Django does not support foreign keys across multiple databases (originally Django 1.3 docs)

But I\'m looking for a workaround.

What doesn\'t work

9条回答
  •  一整个雨季
    2020-12-07 10:01

    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.)

提交回复
热议问题