TypeError:<lambda>()缺少1个必需的位置参数:

时间:2017-12-05 22:40:36

标签: python django lambda factory-boy

我试图使用factory_boy和faker用一些随机数据填充我的Django项目。但是,当我尝试创建UserFactory对象的实例时,我得到错误TypeError :()缺少1个必需的位置参数:&#39; a&#39;。

它似乎与fake_date和date_joined属性及其lambda函数有关。我发现的一些教程已经以这种方式为Factory对象使用lambda函数进行了布局,但它并不适用于我。

import datetime
import factory
import faker
from dataStoreApp.models import Category, Goal, Transaction
from django.contrib.auth.models import User

fake = faker.Faker()


class CategoryFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = Category

    name = factory.Iterator(['Category1', 'Category2',
                             'Category3', 'Category4',
                             'Category5', ], cycle=False)


class UserFactory(factory.django.DjangoModelFactory):
    FACTORY_HIDDEN_ARGS = ('fake_date', )

    class Meta:
        model = User

    fake_date = factory.LazyAttribute(
    lambda a: datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    date_joined = factory.LazyFunction(lambda a: a.fake_date)
    first_name = factory.LazyAttribute(lambda b: fake.first_name())
    last_name = factory.LazyAttribute(lambda c: fake.last_name())
    email = factory.LazyAttribute(lambda e: 'test' + '@test_email.com')



class GoalFactory(factory.DjangoModelFactory):
    class Meta:
        model = Goal


class TransactionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Transaction

在python控制台中运行时,我收到以下错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 568, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "C:\Program Files\Python36\lib\site-packages\factory\base.py", line 505, in _generate
    return step.build()
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 272, in build
    step.resolve(pre)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 221, in resolve
    self.attributes[field_name] = getattr(self.stub, field_name)
  File "C:\Program Files\Python36\lib\site-packages\factory\builder.py", line 363, in __getattr__
    extra=declaration.context,
  File "C:\Program Files\Python36\lib\site-packages\factory\declarations.py", line 59, in evaluate
    return self.function()
TypeError: <lambda>() missing 1 required positional argument: 'a'

1 个答案:

答案 0 :(得分:6)

您可以在代码

中创建带参数a的函数
lambda a: ....

但似乎程序期望没有参数的函数

lambda: ...