I just started using factory boy with Django. It has a parameter FACTORY_DJANGO_GET_OR_CREATE , which means that it will not create a new object if it already exists. But when I query an existing object with an existing SubFactory object, it creates an unused object, despite this parameter.
For example, in a completely new project, I tried:
and
# factories.py import factory from . import models class AFactory(factory.DjangoModelFactory): FACTORY_FOR = models.A FACTORY_DJANGO_GET_OR_CREATE = ('name',) name = factory.Sequence(lambda n: 'A-{0}'.format(n)) class BFactory(factory.DjangoModelFactory): FACTORY_FOR = models.B FACTORY_DJANGO_GET_OR_CREATE = ('name',) name = factory.Sequence(lambda n: 'B-{0}'.format(n)) a = factory.SubFactory(AFactory)
Now:
from factories import * a = AFactory(name="Apple") models.A.objects.all()
Then, the final call to BFactory created a new object of class A , although an object B named Beetle already exists (and is not recreated). Why and how to stop this new object A?
(I know I can get around this by calling instead:
b = BFactory(name="Beetle", a__name="Apple")
but in my actual use case, I have several dependencies and hierarchy levels, and it is useless to provide additional redundant parameters this way - and I cannot get the right combination of parameters.)
Thanks!
source share