gpt4 book ai didi

python - Django + Factory Boy : How to use a named parameter to control behavior of factory. 也许+ factory.RelatedFactory

转载 作者:行者123 更新时间:2023-12-04 02:00:47 29 4
gpt4 key购买 nike

有没有办法定义命名参数(不是模型属性)来控制 factory.Maybe 的行为?

例如:我想创建一个命名参数,通过可能条件控制RelatedFactory的创建,我尝试这样做:

# factories.py
class Purchase(factory.DjangoModelFactory):
user = factory.SubFactory('project.factories.UserFactory')
total = uniform(10, 100)

class Meta:
model = Purchase

class UserFactory(factory.DjangoModelFactory):
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name')

has_purchase = False
purchases = factory.Maybe(
'has_purchase',
yes_declaration=factory.RelatedFactory(Purchase, 'purchase'),
no_declaration=None
)

class Meta:
exclude = ['has_purchase', 'purchases']
model = User

# tests.py
user_without_purchase = UserFactory.create()
user_with_purchase = UserFactory.create(has_purchase=True)

我似乎无法通过命名参数更改has_purchase 的值,它始终设置为False。不知道是不是因为这两个字段都声明在exclude Meta属性中。我必须将它们放在 exclude 中,否则 DjangoModelFactory 在将其保存到数据库时会尝试使用这些字段,这会导致完整性错误。

有办法吗?

最佳答案

工厂男孩似乎有一个功能可以提供额外的参数,而不必将这些字段添加到 exclude 属性:http://factoryboy.readthedocs.io/en/latest/reference.html#simple-parameters :

class UserFactory(factory.DjangoModelFactory):
class Params:
has_purchase = False

http://factoryboy.readthedocs.io/en/latest/reference.html#lazyattribute 结合使用也许?

关于python - Django + Factory Boy : How to use a named parameter to control behavior of factory. 也许+ factory.RelatedFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47435446/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com