Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I use separate database for every application in django

I have app1 and app2, I wanna app1 use db1 and app2 use db2

the approach I found is to using database router, a little bit complicated

I wanna know is there any simple way?

Can I just config it in settings.py

like image 811
davyzhang Avatar asked Sep 02 '25 15:09

davyzhang


1 Answers

No. The correct way is to use routers. It is very simple. See MyAppRouter in django's documentation: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#an-example:

class MyAppRouter(object):
    """A router to control all database operations on models in
    the myapp application"""

    def db_for_read(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in myapp is involved"
        if obj1._meta.app_label == 'myapp' or obj2._meta.app_label == 'myapp':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the myapp app only appears on the 'other' db"
        if db == 'other':
            return model._meta.app_label == 'myapp'
        elif model._meta.app_label == 'myapp':
            return False
        return None
like image 164
Udi Avatar answered Sep 05 '25 10:09

Udi