Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-authenticationdjango-apps

How to use Django models from one app for connection to db replica from second app?


My system consists of two applications which are separate Django projects (let's say A and B) with own default databases and own users. Application B also reads from the application A database replica.

To achieve such behaviour I included application A into B's INSTALLED_APPS and can access db replica through its models. But everything that is related to users (permissions, groups) is messed.

Does using django.contrib.auth in both applications led to this behaviour, and is there a better solution to work with replica through Django ORM?


Solution

  • Indeed there is a better way. In django world it called DatabaseRouter.

    You can read about it here: https://docs.djangoproject.com/en/2.1/topics/db/multi-db/

    It is a very comprehensive guide how to achieve multi db env for your django app.

    And you can always write custom DatabaseRouter class which allows you to define behavior like: read only, write only, full access per app label, or even your model name.

    You can even do this manually (but I will not recommend this for you - as this probably require a lot of changes in the current codebase:

    >>> # So will this.
    >>> Author.objects.using('default').all()
    
    >>> # This will run on the 'other' database.
    >>> Author.objects.using('other').all()
    

    Hope that help - if you have more questions - please ask.