city
city

Reputation: 261

Multiple database help? (django)

So I read over the multiple database docs at https://docs.djangoproject.com/en/dev/topics/db/multi-db/ and it was decently helpful. I got how to show second database in setting.py and how to sync it via command prompt. but what I can't figure out is how to specify how to make a certain model get synced to/saved in a second database. especially if i haven't explicitly stated it.

Like users.

If I'm using django's users class to create users and such how can I get that saved to the second database?

Upvotes: 0

Views: 341

Answers (2)

niko.makela
niko.makela

Reputation: 547

(Code directly from Django DOCS: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#automatic-database-routing

Routers handles in which database the data should be get or set.

If you want a router for your application (named 'myapp')

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

By adding next line to settings.py, all 'myapp' applications data will be created/saved/handled in it's own database (named "other"). All the rest of the applications uses the default database.

DATABASE_ROUTERS = ['path.to.MyAppRouter']

The router can be saved where ever you want. Just fix the path of settings.DATABASE_ROUTERS.

Upvotes: 1

okm
okm

Reputation: 23871

Please read the doc you provided again and carefully. The Automatic databse routing section of the doc answers your question exactly.
The routing of User DB depends on your actual usage and partition policy, there is not one sentence answer. There are examples inside the document for User, you could read and check in your local machine.

Upvotes: 1

Related Questions