TLTR: Django does not include database names in SQL queries, can I somehow 
force it to do this, or is there a workaround?

The long version:

I have two unmanaged legacy MySQL databases (Note: I have no influence on 
the DB layout) for which I'm creating a readonly API using DRF on Django 
1.11 and python 3.6 

I'm working around the referential integrity limitation of MyISAM DBs by 
using the SpanningForeignKey field suggested here: 
https://stackoverflow.com/a/32078727/7933618

I'm trying to connect a table from DB1 to a table from DB2 via a ManyToMany 
through table on DB1. That's the query Django is creating:
  
SELECT "table_b"."id" FROM "table_b" INNER JOIN "throughtable" ON ("table_b"
."id" = "throughtable"."b_id") WHERE "throughtable"."b_id" = 12345

Which of course gives me an Error "Table 'DB2.throughtable' doesn't exist" 
because throughtable is on DB1 and I have no idea how to force Django to 
prefix the tables with the DB name. The query should be:
   
SELECT table_b.id FROM DB2.table_b INNER JOIN DB1.throughtable ON (table_b.id 
= throughtable.b_id) WHERE throughtable.b_id = 12345

Models for app1 `db1_app/models.py`:

    class TableA(models.Model):
        id = models.AutoField(primary_key=True)
        # some other fields
        relations = models.ManyToManyField(TableB, through='Throughtable')


    class Throughtable(models.Model):
        id = models.AutoField(primary_key=True)
        a_id = models.ForeignKey(TableA, to_field='id')
        b_id = SpanningForeignKey(TableB, db_constraint=False, to_field='id'
)

Models for app2 `db2_app/models.py`:

    class TableB(models.Model):
        id = models.AutoField(primary_key=True)
        # some other fields

Database router:

    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'db1_app':
            return 'DB1'
        
        if model._meta.app_label == 'db2_app':
            return 'DB2'

        return None

Can I force Django to include the database name in the query? Or is there 
any workaround for this?

I also posted this question on StackOverflow - to no avail, so I'll try 
here.
https://stackoverflow.com/questions/45018277/django-manytomany-through-with-multiple-databases

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0f4e3da3-7fbe-4abf-a3a4-77bb0415e6a0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to