gpt4 book ai didi

django - 工厂男孩 : define field that depends on other field

转载 作者:行者123 更新时间:2023-12-04 05:29:46 28 4
gpt4 key购买 nike

如何使用 factory-boy 定义依赖于其他字段的字段?

例如,我想定义一个 email这取决于 first namelast nameUser .

我尝试使用 post_generation装饰器。但是,我的系统需要在创建实例之前定义电子邮件。

最佳答案

使用 LazyAttribute :

from the docs:

The LazyAttribute is a simple yet extremely powerful building brick for extending a Factory.

It takes as argument a method to call (usually a lambda); that method should accept the object being built as sole argument, and return a value.

class UserFactory(factory.Factory):
class Meta:
model = User

username = 'john'
email = factory.LazyAttribute(lambda o: '%s@example.com' % o.username)
lazy_attribute装饰器。

from the docs:

If a simple lambda isn’t enough, you may use the lazy_attribute() decorator instead.

This decorates an instance method that should take a single argument, self; the name of the method will be used as the name of the attribute to fill with the return value of the method:

class UserFactory(factory.Factory)
class Meta:
model = User

name = u"Jean"

@factory.lazy_attribute
def email(self):
# Convert to plain ascii text
clean_name = (unicodedata.normalize('NFKD', self.name)
.encode('ascii', 'ignore')
.decode('utf8'))
return u'%s@example.com' % clean_name

关于django - 工厂男孩 : define field that depends on other field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33965786/

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