Support for Double underscore '__' traverse when relationships are between models from two different databases?

class A(models.Model): 
    id = models.AutoField(primary_key=True)
    b = models.ForeignKey(B, on_delete=models.CASCADE, db_constraint=False )
class B(models.Model):
    someinfo = model.CharField()

# model A are from db named 'database2'
# model B are from db named 'default'

DB router is correctly set for both models using the app label of each model.
Model A and B are from two different Django apps, and are put together here for simplicity.

Now if I do

A.objects.all().values('b__someinfo')

I wouldn’t get any value for ‘b__someinfo’ as b ‘does not exist in database2’ despite I have correctly set the db router to route to ‘default’ for model B and route to ‘database2’ for model A.

I have read that there are limitations for multi db relations in Django, just wants to know if I’m doing anything wrong here or will this be supported anytime soon.

Quoting directly from the docs at Cross-database relations:

Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.

So no, what you’re trying isn’t going to work.

As far as it ever being supported, :man_shrugging: . I’m sure if someone came up with a way of handling this that didn’t cause more potential problems than it solves, it would be considered.

1 Like