如何使用 FactoryBoy 指定列表大小
How to specify list size using FactoryBoy
假设我有这个模型:
class FooContainerModel(object):
def __init__(self, foos):
self.foos = foos
我希望能够决定在创建时将创建多少个 foo,例如。
model = FooContainerFactory(count=15)
试过像
这样的工厂
class FooContainerFactory(factory.Factory):
class Meta:
model = FooContainerModel
foos = factory.List([Foo() for _ in xrange(20)]) # fixed amount
foos = factory.lazy_attribute(lambda o: [Foo() for _ in xrange(20)]) # same
当然,我可以手动创建具有所需长度的 Foo() 列表并实例化 FooContainerModel,但这不是我想要的。有什么解决办法吗?
我不知道 FactoryBoy 是如何工作的,但是当我需要 Django 模型中字段的动态属性时,这种策略通常对我有用:
def FooContainerFactory(factory.Factory):
def __init__(self, count=20, *args, **kwargs):
self.foos = factory.List([Foo() for _ in range(20)])
super(FooContainerFactory, self).__init__(*args, **kwargs)
class Meta:
model = FooContainerModel
您可以使用 create_batch
方法。
models = FooContainerFactory.create_batch(size=15)
假设我有这个模型:
class FooContainerModel(object):
def __init__(self, foos):
self.foos = foos
我希望能够决定在创建时将创建多少个 foo,例如。
model = FooContainerFactory(count=15)
试过像
这样的工厂class FooContainerFactory(factory.Factory):
class Meta:
model = FooContainerModel
foos = factory.List([Foo() for _ in xrange(20)]) # fixed amount
foos = factory.lazy_attribute(lambda o: [Foo() for _ in xrange(20)]) # same
当然,我可以手动创建具有所需长度的 Foo() 列表并实例化 FooContainerModel,但这不是我想要的。有什么解决办法吗?
我不知道 FactoryBoy 是如何工作的,但是当我需要 Django 模型中字段的动态属性时,这种策略通常对我有用:
def FooContainerFactory(factory.Factory):
def __init__(self, count=20, *args, **kwargs):
self.foos = factory.List([Foo() for _ in range(20)])
super(FooContainerFactory, self).__init__(*args, **kwargs)
class Meta:
model = FooContainerModel
您可以使用 create_batch
方法。
models = FooContainerFactory.create_batch(size=15)