[Fixed]-Django ORM – confusion about Router.allow_relation()

25👍

That’s a good question, and I agree that the multiple-database docs are not as clear as they could be.

The thing to keep in mind is that there are basically two use cases for multi-DB: putting different data (models) on different databases; and setting up a primary / replica DB structure. These use cases are both represented in the primary example in the documentation.

In the different-data scenario, you definitely want allow_relation() to reject any relations between two different databases since there’s no way to enforce constraints across databases. But in the primary-replica scenario, you have the same data on all the databases, so it’s OK to allow relations between any of them.

So if you get one model instance from replica1 and another from replica2 (due to the random choice of database for reads), it would be OK to allow a relation between them since the same data exists on primary, and that’s where the new model data will be written.

Leave a comment