I'm using factory_boy to replace fixtures in a Django app. I have a Product model that should have many Offers and Merchants.
#models.py
class Product(models.Model):
name = models.CharField()
class Merchant(models.Model):
product = models.ForeignKey(Product)
name = models.CharField()
class Offer(models.Model):
product = models.ForeignKey(Product)
price = models.DecimalField(max_digits=10, decimal_places=2)
I want a factory that creates a Product with several Merchants and several Offers.
#factories.py
import random
from models import Offer, Merchant, Product
class OfferFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = Offer
product = factory.SubFactory(ProductFactory)
price = random.randrange(0, 50000, 1)/100.0
class MerchantFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = Merchant
product = factory.SubFactory(ProductFactory)
name = factory.Sequence(lambda n: 'Merchant %s' % n)
url = factory.sequence(lambda n: 'www.merchant{n}.com'.format(n=n))
class ProductFactory(factory.django.DjangoModelFactory):
FACTORY_FOR = Product
name = "test product"
offer = factory.RelatedFactory(OfferFactory, 'product')
offer = factory.RelatedFactory(OfferFactory, 'product') # add a second offer
offer = factory.RelatedFactory(OfferFactory, 'product') # add a third offer
merchant = factory.RelatedFactory(MerchantFactory, 'product')
merchant = factory.RelatedFactory(MerchantFactory, 'product') # add a second merchant
merchant = factory.RelatedFactory(MerchantFactory, 'product') # add a third merchant
But when I use ProductFactory to create a Product, it only has one offer and one merchant.
In [1]: from myapp.products.factories import ProductFactory
In [2]: p = ProductFactory()
In [3]: p.offer_set.all()
Out[3]: [<Offer: $39.11>]
How do I set up a ProductFactory to have more than one dependent of a particular type?
offer
just be re-pointed to the output of the next execution offactory.RelatedFactory
as the OP intended? Why doesfactory.RelatedFactory
have to be assigned to something to execute? – Nervous