我正在为一个模型工厂工作,我正在尝试填充一个有选择列表的字段。当我尝试使用Factory创建一个对象时,我尝试从选项列表中填写一个随机选项,抛出异常:
TypeError:' choice'是此函数的无效关键字参数
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 551, in build
return cls._generate(enums.BUILD_STRATEGY, kwargs)
File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 505, in _generate
return step.build()
File "/usr/local/lib/python2.7/dist-packages/factory/builder.py", line 279, in build
kwargs=kwargs,
File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 312, in instantiate
return self.factory._build(model, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/factory/base.py", line 531, in _build
return model_class(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 571, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'choice' is an invalid keyword argument for this function
使用的版本:
django==1.11
factory-boy==2.9.2
python==2.7.12
(裁剪)模型:
class Server(models.Model):
TEST = 'test'
ACCEPT = 'accept'
SERVER_TYPES = (
(TEST, _("Testing Server")),
(ACCEPT, _("Acceptation Server"))
)
type = models.CharField(_("Server type"), max_length=50, choices=SERVER_TYPES)
(裁剪)工厂:
class ServerFactory(factory.DjangoModelFactory):
type = factory.Faker('random_element', elements=[choice[0] for choice in Server.SERVER_TYPES)
class Meta:
model = Server
我没有使用Faker('random_element, elements=[..])
,而是尝试使用LazyFunction
:
def get_server_type():
choices = [choice[0] for choice in Server.SERVER_TYPES]
return random.choice(choices)
class ServerFactory(factory.DjangoModelFactory):
organization = factory.SubFactory(OrganizationFactory)
type = factory.LazyFunction(get_server_type)
.. Meta ..
这也会引发同样的错误。我也找不到任何其他替代方法来解决这个问题。有关使用type
包时如何使用SERVER_TYPES
个选项填充factory
字段的任何建议吗?
答案 0 :(得分:2)
你能尝试一下吗?
from random import choice
type = factory.LazyAttribute(lambda x: choice(Server.SERVER_TYPES)[0])
基于对问题的初步描述的旧评论:
应为type = factory.Faker('random_element', elements=[choice[0] for choice in Server.SERVER_TYPES])