Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 973
Houman Avatar asked Oct 24 '14 14:10

Houman


2 Answers

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')
    ...
like image 109
Alex Lisovoy Avatar answered Sep 28 '22 13:09

Alex Lisovoy


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

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

    ...
like image 28
eLRuLL Avatar answered Sep 28 '22 13:09

eLRuLL