Multiple django databases for different apps

Hi,
I have a Django project with 2 apps, blog and shop.
I would like the blog app to use the default database (normal behaviour) and the shop app to use a different database. Is that possible ? Can I define the db used in the AppConfig?
Thanks a lot,
Thomas

It’s possible, but you would need to use a custom database router to do it. It’s not a setting that can be made in AppConfig.

See Automatic database routing.

Hi, I already had a look at the documentation, so if I well understand, I need to define a ShopRouter for my “shop” app. But then I’ll need to change all my views with the using() in the query?

No, the purpose of the Router is to prevent you from having to specify using with your queries.

To expand a bit on this, the routers are designed to specify where to put/get data to/from on a model-class level. So in this case, in the methods db_for_read and db_for_write you check if the model in the arguments is from the shop app and, when that is true, return the corresponding database name. In allow_migrate you check if the model is from the shop app and the database is the shop database.

Things get trickier if you have data from the same model class that needs to be pulled from different databases. For example, maybe you need somewhat different users for the blog and shop, but shop users are required to be saved in the shop database.

Things will get trickier still if you need multiple databases (for multiple shops), but from what I gather this isn’t the case here, so nothing to worry about.

Hi all, thanks for the feedbacks. I am struggling because in both apps I use a Custom User Model, I need to understand how to manage this.

I wouldn’t suggest that.

If you’ve got one “site”, you want one authoritative source of identification. So much of Django internally is built around having one User model.

Now, you could have different Profile models, but then you’re dealing with the issues around cross-database relationships.

Mostly, I’d suggest to you in the strongest possible terms to re-think your architecture if you think this is the way you want to go.

My earlier example of different users was perhaps ill-chosen. I meant to illustrate that you can have one model fetch data from different databases based on criteria not inherent to the model class (and how this is tricky do right). I have to agree with Ken here in that the user model is special and you probably don’t want to to split this across multiple databases.