ManyToMany与使用factory_boy的直通模型的关系?

时间:2016-02-15 14:23:25

标签: django python-2.7 unit-testing factory

我在使用工厂通过模型创建多对多关系时遇到问题。我点了这个链接factory recipies。 我收到TypeError: 'datetime.date' object is not callable此错误。帮我找到解决方案。

我又出了一个错误:

File "/local/lib/python2.7/site-packages/factory/base.py", line 492, in _generate
     obj = cls._prepare(create, **attrs)

File "/local/lib/python2.7/site-packages/factory/base.py", line 467, in _prepare
    return cls._create(model_class, *args, **kwargs)

File "/local/lib/python2.7/site-packages/factory/django.py", line 174, in _create
  return manager.create(*args, **kwargs)

File "/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
  return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/local/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create
  obj = self.model(**kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__
   raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])


TypeError: 'a1' is an invalid keyword argument for this function

models.py

class TimeStampModel(models.Model):
    start_date = models.DateField(_('Start Date'))
    end_date = models.DateField(_('End Date'))

    class Meta:
        abstract = True

class User(models.Model):
    name = models.CharField()

class Aclass(models.Model):
    name = models.CharField()
    user = models.ForeignKey(User)
    report = models.ManyToManyField('self', through='Bcalss')

class Bcalss(TimeStampModel):
    a1 = models.ForeignKey(Aclass)
    b1 = models.ForeignKey(Aclass)

factories.py

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.User

    name = "John Doe"

class AclassFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Aclass
    user = factory.SubFactory(UserFactory)
    name = "Admins"

class BclassFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Bclass

    a1 = factory.SubFactory(AclassFactory)
    b1 = factory.SubFactory(AclassFactory)
    start_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=2))
    end_date = fuzzy.FuzzyDate(timezone.localtime(timezone.now())).date(), timezone.localtime(timezone.now())).date() + timedelta(days=6))

class AclassWithBclassFactory(AclassFactory):
    reports = factory.RelatedFactory(BclassFactory, 'a1')

tests.py

class A1classModelTestCase(TestCase):

    def test_a1class_create(self):
        a1 = factories.AclassWithBclassFactory.create()

1 个答案:

答案 0 :(得分:0)

在这一行:

start_date = factory.LazyAttribute(datetime.today)

您需要使用()实际调用该函数:

start_date = factory.LazyAttribute(datetime.today())