Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
How to specify the database for Factory Boy? #171
The answer on stackoverflow is perfectly valid; I'll copy it here for future reference:
Simply override the
@classmethod def _get_manager(cls, model_class): manager = super(MyCustomFactory, cls)._get_manager(model_class) return manager.using('global')
With Django, the reference database is often managed at the model level, using a database router (see https://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-routers).
In your situation, I guess this wasn't sufficient; could you describe your setup so I can see whether I could provide support within factory_boy ?
I'm running into the same issue, my setup:
if IS_UNITTEST: DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3' DATABASES['default']['TEST_MIRROR'] = 'master' DATABASES['default']['TEST_DEPENDENCIES'] = ['master'] DATABASES['master']['ENGINE'] = 'django.db.backends.sqlite3' DATABASES['master']['TEST_DEPENDENCIES'] = 
Our app mainly reads and just recently we needed to introduce a separate master DB. Of course I could make the write DB 'default' and change the former default into slave but I feel that should not be motivated by testsuite issues.
I've changed the _get_manager() method to actually use the django db routing and that seems to work nicely:
import factory from django.db.utils import ConnectionRouter class ModelFactory(factory.DjangoModelFactory): @classmethod def _get_manager(cls, model_class): manager = super(ModelFactory, cls)._get_manager(model_class) router = ConnectionRouter() db = router.db_for_write(model_class) return manager.using(db) class ArticleFactory(ModelFactory): FACTORY_FOR = Article
Of course I can issue a pull request.
Thanks for the use case, which I hadn't identified (the app just reads, but tests need to write to another database).
I was thinking along the lines of:
class ArticleFactory(factory.django.DjangoModelFactory): class Meta: model = models.Article database = 'master'
Apparently I totally forgot to get back to this issue.
As to the monkeypatch question. My first question would be: Why? Do you really need a single factory to use different databases? If possible just make it part of your manager.
If varying per test is needed, I suppose the
You'd end up with something like this:
Sidenote: I have the feeling issue tracker is not the best place for support,
the Context Manager idea looks promising, @TBeijen I would really appreciate if you could share a working example of that. I tried to implement one by myself but got stuck on overriding a @classmethod and how to pass the database name to
I also created a SO question about it.