[Django]-Django with multiple databases and foreignkeys for User

4👍

The answer to question 1 is: Yes.

What you will need in any case is a database router (The example in the Django docs is exactly about the auth app, so there’s no need to copy this code here).

The answer to question 2 is: Maybe. Not officially. It depends on how you have set up MySQL:

https://docs.djangoproject.com/en/dev/topics/db/multi-db/#limitations-of-multiple-databases

Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases.

This is because of referential integrity.

However, if you’re using SQLite or MySQL with MyISAM tables, there is no enforced referential integrity; as a result, you may be able to ‘fake’ cross database foreign keys. However, this configuration is not officially supported by Django.

I have a setup with several legacy MySQL DBs (readonly). This answer shows How to use django models with foreign keys in different DBs?

I later ran into troubles with Django ManyToMany through with multiple databases and the solution (as stated in the accepted answer there) is to set the table name with quotes:

class Meta:    
    db_table = '`%s`.`table2`' % db2_name

Related questions that might provide some additional information:

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

How to use django models with foreign keys in different DBs?

It would be nice if somebody would take all this information and put in into the official Django doc 🙂

Leave a comment