Houman
Houman

Reputation: 66320

How to specify the database for Factory Boy?

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)

Upvotes: 7

Views: 1756

Answers (2)

eLRuLL
eLRuLL

Reputation: 18799

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

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

    ...

Upvotes: 3

Alex Lisovoy
Alex Lisovoy

Reputation: 6065

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')
    ...

Upvotes: 3

Related Questions