I have a website which is using two databases. I have a router set up as stated in the django documentation. The routing works fine when I use the runserver. However I wasn’t able to test it using LiveServerTestCase. The queryset is empty.
I assume that the fixtures are not loaded correctly into the second database.
The test works if I remove the database router (and therefore only use one db).
Here is my Router config:
class ScreenerRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'screener':
return 'filemaker'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'screener':
return 'filemaker'
return None
def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label == 'screener' or obj2._meta.app_label == 'screener':
return True
return None
def allow_syncdb(self, db, model):
if db == 'filemaker':
return model._meta.app_label == 'screener'
elif model._meta.app_label == 'screener':
return False
return None
I have set multi_db = True in the TestCase.
Another issue was that dumpdata –database=filemaker screener.ScreenerRouter returns an empty array, even though there are entries in the DB. I can even edit them in the DjangoAdmin. I had to copy the data to the default DB and dump it from there.
I figured out the problem. I had multiple apps that needed access to the ‘filemaker’ database and each one had its own router.
The routers were processed in order. But the allow_syncdb method of the first router already returned a value which prevented syncdb and dumpdata for all other apps.
The solution was to write one MasterRouter for the filemaker db and put all apps in there.
As in: