如何将14天添加到变量值?

时间:2013-02-28 15:54:30

标签: python django

我使用工厂男孩,这是我的工厂:

class ConFactory(factory.Factory):
    FACTORY_FOR = Con

    user = factory.SubFactory(UserFactory)
    category = '1'
    number = '12345678'
    time_start = factory.Sequence(lambda n:(datetime.now() + timedelta(days=n)).date(), int)
    time_end = factory.Sequence(lambda n:(datetime.now() + timedelta(days=n+100)).date(), int)
    reminder = datetime.now()

如何将reminder设置为time_start + 14天

reminder = time_start + 14 days

2 个答案:

答案 0 :(得分:0)

 from datetime import timedelta
 reminder = datetime.now() + timedelta(14)

但是,您无法在初始化中添加time_start,因此您可以在save()函数中添加一个挂钩:

 def save(self, *args, **kwargs):
     if self.time_start:
         self.reminder = self.time_start + timedelta(14)
     super(ConFactory, self).save(*args, **kwargs)

如果您之前未覆盖model属性,则会提供更多信息here

答案 1 :(得分:0)

如果要根据其他属性值设置属性值,则需要使用Lazy Attributes

在您的情况下,您应该从datetime导入timedelta并将此行放在您的工厂中:

reminder = factory.LazyAttribute(
    lambda con_factory: con_factory.time_start + timedelta(14)
)

有关详细信息,请参阅this