我正在使用 factory_boy 替换 Django 应用程序中的固定装置。我有一个产品模型,它应该有很多优惠和商家。
#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)
我想要一个创建具有多个商家和多个报价的产品的工厂。
#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
但是当我使用 ProductFactory 创建一个产品时,它只有一个报价和一个商家。
In [1]: from myapp.products.factories import ProductFactory
In [2]: p = ProductFactory()
In [3]: p.offer_set.all()
Out[3]: [<Offer: $39.11>]
如何将 ProductFactory 设置为具有多个特定类型的依赖项?