[Django]-Django – 1 database per model?

2👍

Django can not split migrations between databases for an application, see https://docs.djangoproject.com/en/1.9/topics/db/multi-db/#allow_migrate.

You have several options:

  1. Let django migrate all models to both databases, and then one table will be left empty on each database. You will need a db router on a row basis, and give the router a hint what database the object belongs to. The read/write routing, unlike migrations, does give the option to decide on the database based on the model (and not only the app).

  2. Same as 1, but to be safe, run a custom DROP TABLE statement for table A on database2, and for table B on database 1. If you will make some routing mistakes, you will get an exception

  3. Split your app. Although django is geared to couple data and functionality together in the same app, you can split an app when needed. In your case, into three:

    • app1 with model A
    • app2 with model B
    • app3 with the views,url, tests etc that will access the database layer in app1, app2.

See Django models across multiple projects/microservices. How to?

1👍

Looks like it is possible.
You should setup all databases in the settings DATABASES.
And after that you can write custom database router like it is described here: https://docs.djangoproject.com/en/1.9/topics/db/multi-db/#using-routers

But I believe that you have ready read that.
More interesting question is what about mirations? And looks like there an option to play with – it is allow_migrate from here. https://docs.djangoproject.com/en/1.9/topics/db/multi-db/#an-example
I would try to place here custom logic to handle database miration into the right DB.

👤Paul

Leave a comment