# Problems with multiple databases migrations and tests

**URL:** <https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510>\
**Category:** Using Django\
**Created:** [December 2, 2020, 12:37pm UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510 "2020-12-02T12:37:12Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![shahwan42](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/shahwan42/32/2190_2.png) [@shahwan42](https://forum.djangoproject.com/u/shahwan42)\
**Post date:** [December 2, 2020, 12:37pm UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510/1 "2020-12-02T12:37:12Z")

</div>

Hello there,

I’m currently adding another database to save models of _newapp_ only inside it.  
I want all the other applications to save their models inside the default one as before.

```
"newapp_db": {
    "ENGINE": "django.db.backends.postgresql",
    "NAME": env("NEWAPP_POSTGRES_DB"),
    "USER": env("NEWAPP_POSTGRES_USER"),
    "PASSWORD": env("NEWAPP_POSTGRES_PASSWORD"),
    "HOST": env("NEWAPP_POSTGRES_HOST"),
    "PORT": env("NEWAPP_POSTGRES_PORT"),
    "TEST": {"NAME": "newapptest"},
    "CONN_MAX_AGE": 60 if DEPLOYMENT != "LOCAL" else 0,
    "ATOMIC_REQUESTS": True,
},

```

I also added this setting:  
`DATABASE_ROUTERS = ["path.to.NewappRouter"]`

And this is the code for the NewappRouter:

```
class NewappRouter:
    """
    A router to control all database operations on models in the
    newapp application.
    """

    route_app_labels = {"newapp"}

    def db_for_read(self, model, **hints):
        """
        Attempts to read newapp models go to cardtokens_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return "newapp_db"
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write newapp models go to newapp_db.
        """
        if model._meta.app_label in self.route_app_labels:
            return "newapp_db"
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations for newapp app only.
        """
        if (
            obj1._meta.app_label in self.route_app_labels
            and obj2._meta.app_label in self.route_app_labels
        ):
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the newapp app only appear in the
        'newapp_db' database.
        """
        if app_label in self.route_app_labels:
            return db == "newapp_db"
        return False

```

\*\*Problems: \*\*

- When I run `manage.py migrate`, migrations from _newapp_ are applied to the default database. Then when I run `manage.py migrate --database=newapp_db` the other apps migrations get applied to the `newapp_db`! And both cases should be prevented by the router according to the [documentation](https://docs.djangoproject.com/en/dev/topics/db/multi-db/#database-routers)
- When I run `manage.py test` I get the errors `AssertionError: Database connections to 'newapp_db' are not allowed in this test. Add 'newapp_db' to path.to.TestCaseName.databases to ensure proper test isolation and silence this failure.` which also should be prevented by the router!

Knowing that I inspected the databases using `manage.py dbshell` and found that the operations are done as desired, newapp models are saved into _newapp\_db_ and not in the _default_

Any ideas what might be the problem?

Thanks.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 2, 2020, 3:50pm UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510/2 "2020-12-02T15:50:45Z")

</div>

Have you verified that the tables, etc are actually being created in the wrong databases?

Migrations will show the migrations as being applied, but if the router is working correctly, nothing happens.

For example, I added a “newapp” app to a system with your router, and made appropriate configuration changes. I ran makemigrations - the migration was created properly.  
I then ran migrate, and it showed that the migration ran, but an inspection of the database also shows that the tables were not created.  
I _then_ ran migrate with the `--database newapp_db` parameter. It likewise showed that all the migrations ran, but the only tables created were in my newapp models.

---

<div class="post-metadata">

**Author:** ![shahwan42](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/shahwan42/32/2190_2.png) [@shahwan42](https://forum.djangoproject.com/u/shahwan42)\
**Post date:** [December 3, 2020, 12:50pm UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510/3 "2020-12-03T12:50:44Z")

</div>

Thank you. I double-checked and I have the same results. It seems like Django prints the migrations anyway.

And we worked around the tests issue by adding `databases = {"default", "newapp_db"}` to every TestCase using a mixin:

```auto
class MultiDbMixin:
    databases = {"default", "newapp_db"}

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 3, 2020, 12:58pm UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510/4 "2020-12-03T12:58:59Z")

</div>

> [@shahwan42](#):
>
> Thank you. I double-checked and I have the same results. It seems like Django prints the migrations anyway.

The migration is “applied” whether or not the migrations actually change a database. While I don’t know all the specific reasons why it was done this way, it does makes sense to me. Migrations have a specific order that they need to be run, and so a later migration needs to know that all the previous migrations have completed. (You will find the django\_migrations table in every database used for migrations - that’s where this tracking is stored.)

---

<div class="post-metadata">

**Author:** ![Timeless-py](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/timeless-py/32/3344_2.png) [@Timeless-py](https://forum.djangoproject.com/u/Timeless-py)\
**Post date:** [February 18, 2021, 11:17am UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510/5 "2021-02-18T11:17:01Z")

</div>

I had the same problem, then I added the following:

```python

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label in self.route_app_labels and obj2._meta.app_label in self.route_app_labels:
            return True

        elif self.route_app_labels not in [obj1._meta.app_label, obj2._meta.app_label]:
            return None
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'newapp_db'
        elif db == 'newapp_db':
            return False
        return None

```

---

<div class="post-metadata">

**Author:** ![Timeless-py](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/timeless-py/32/3344_2.png) [@Timeless-py](https://forum.djangoproject.com/u/Timeless-py)\
**Post date:** [February 18, 2021, 11:42am UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510/6 "2021-02-18T11:42:07Z")

</div>

What excatly mean with “relations” ? What is happening exactly on ‘def allow\_relation’?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 18, 2021, 1:23pm UTC](https://forum.djangoproject.com/t/problems-with-multiple-databases-migrations-and-tests/5510/7 "2021-02-18T13:23:06Z")

</div>

The [allow\_relation](https://docs.djangoproject.com/en/3.1/topics/db/multi-db/#allow_relation) method is explained on the [Multiple databases](https://docs.djangoproject.com/en/3.1/topics/db/multi-db/) page.
