Thibault
Thibault

Reputation: 556

django database router cannot import name connection

i have issue with the DB Router on Django 1.4 (python 2.6). I have follow the documentation (https://docs.djangoproject.com/en/dev/topics/db/multi-db/#automatic-database-routing) but when i run my server i have this following error message:

django.core.exceptions.ImproperlyConfigured: Error importing database router MyDBRouter: "cannot import name connection"

My settings.py

DATABASES = {
    'default': {
        ...
    },
    'other' : {
        ...
    }
}
DATABASE_ROUTERS = ['core.models.MyDBRouter',]

here the db router code :

class MyAppRouter(object):
    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

I have try to replace None by 'default' but it still doesn't work.

Upvotes: 1

Views: 3202

Answers (4)

pseudosudo
pseudosudo

Reputation: 6590

For me the problem was coded in the __init__.py file of one of my apps. I think init files are direct dependencies of the settings.py file, and this may lead to cyclic imports.

Upvotes: 0

nuts
nuts

Reputation: 783

Like Zakum is saying in his solution,

if the above mentioned solutions don't work for you, see if you did an import

from django.db.models import Model

in any of your routing-files. If so, you have to remove that.

Upvotes: 1

Zakum
Zakum

Reputation: 2287

That did no good to me, I posted my solution here https://stackoverflow.com/a/17888067/978912, maybe it can save someone the pain of debugging through endless import chains. :)

Upvotes: 1

Thibault
Thibault

Reputation: 556

I have solved this probleme by adding "from django.db import connections" on settings.py

151 # Database router                                                                                                                                       
152 from django.db import connections
153 DATABASE_ROUTERS         = ['core.models.MyDBRouter',]

Now the server run fine! But router is just IGNORED by django -> To fix it, never save Router in models ! create new file

Upvotes: 4

Related Questions