How to specify the database for Factory Boy?
Asked Answered
P

2

7

FactoryBoy seem to always create the instances in the default database. But I have the following problem.

cpses = CanonPerson.objects.filter(persons__vpd=6,
                                   persons__country="United States").using("global")

The code is pointing to the global database. I haven't found a way to specify the database within the factory:

class CanonPersonFactory(django_factory.DjangoModelFactory):
    class Meta:
        model = CanonPerson
        django_get_or_create = ('name_first', 'p_id')
    p_id = 1
    name_first = factory.Sequence(lambda n: "name_first #%s" % n)

    @factory.post_generation
    def persons(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for person in extracted:
                self.persons.add(person)
Pragmatism answered 24/10, 2014 at 14:41 Comment(0)
S
3

Looks like Factory Boy does not provide this feature from box, but you can easily add it manually:

class CanonPersonFactory(django_factory.DjangoModelFactory):
    class Meta:
        model = CanonPerson
    ...
    @classmethod
    def _get_manager(cls, model_class):
        manager = super(CanonPersonFactory, cls)._get_manager(model_class)
        return manager.using('global')
    ...
Syllabify answered 24/10, 2014 at 16:14 Comment(0)
A
3

This is now directly supported by adding the database attribute on Meta:

class CanonPersonFactory(django_factory.DjangoModelFactory):
    class Meta:
        model = CanonPerson
        database = 'global'

    ...
Alodium answered 13/2, 2018 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.