如何创建工厂男孩与几个孩子



我有两个Django模型:

class Country(models.Model):
    country_name = models.CharField(max_length=10)
class Resident(models.Model):
    country = models.ForeignKey('Country')
    name = models.CharField(max_length=10)
    age = models.PositiveSmallInteger()

和我想要Factory Boy创建一个Country,有两个具有不同属性的子节点。

例如,somefactory.create()创建FooCountry, FooCountry有两个居民:

name=Paul, country=foo, age=33
name=Jamse, country=foo, age=34

怎么做?

首先写下CountryFactoryResidentFactory(如FactoryBoy文档中所述)。然后写函数:

def create_country_with_residents():
    country = CountryFactory.create()
    ResidentFactory.create(country=country, name=Paul, age=33)
    ResidentFactory.create(country=country, name=James, age=34)
    return country

最新更新