如何为Factory Boy指定数据库?

时间:2014-10-24 14:41:56

标签: python django factory-boy

FactoryBoy似乎总是在默认数据库中创建实例。但我有以下问题。

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

代码指向global数据库。我还没有找到在工厂中指定数据库的方法:

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)

2 个答案:

答案 0 :(得分:3)

看起来Factory Boy不提供此功能,但您可以轻松手动添加:

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

答案 1 :(得分:1)

现在可以通过在database添加Meta属性直接支持:

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

    ...