First, I'll be honest with you: I do not know if this is the best answer or if it follows the good practices of python.
Anyway, the solution that I found for this kind of scenario was to use post_generation.
import factory
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
name = factory.Faker('name'))
@factory.post_generation
def with_purchased_products(self, create, extracted, **kwargs):
if extracted is not None:
PurchaseFactory.create(user=self, with_products=extracted)
class PurchaseFactory(factory.DjangoModelFactory):
class Meta:
model = Purchase
user = factory.SubFactory(UserFactory)
@factory.post_generation
def with_products(self, create, extracted, **kwargs):
if extracted is not None:
ProductFactory.create_batch(extracted, purchase=self)
class ProductFactory(factory.DjangoModelFactory):
class Meta:
model = Product
purchase = factory.SubFactory(PurchaseFactory)
To make this work you just need to:
UserFactory.create(with_purchased_products=10)
And this is just a article that is helping learn more about Django tests with fakes & factories. Maybe can help you too.