How to specify the database for Factory Boy?

孤者浪人 提交于 2020-01-02 03:28:07

问题


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)

回答1:


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



回答2:


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

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

    ...


来源:https://stackoverflow.com/questions/26550262/how-to-specify-the-database-for-factory-boy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!