How to specify database for Factory Boy?

FactoryBoy seems to always create 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 points to the global database. I did not find a way to specify the database in 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) 
+6
source share
2 answers

Factory Boy doesn't seem to provide this feature from the window, 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') ... 
+3
source

This is now directly supported by the addition of the database attribute in Meta :

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

Source: https://habr.com/ru/post/977185/


All Articles