简体   繁体   English

使用 Factory Boy SelfAttribute + relativedelta

[英]Using Factory Boy SelfAttribute + relativedelta

I'm using Factory Boy in my tests and want to achieve the following:我在测试中使用 Factory Boy 并希望实现以下目标:

  • Make first_period_end_date dependent on first_period_date and add 12 months to it.使first_period_end_date依赖于first_period_date并添加 12 个月。

I'm trying to use SelfAttribute in combination with relativedelta but the way I'm currently applying it doesn't work.我正在尝试将SelfAttributerelativedelta结合使用,但我目前应用它的方式不起作用。 My code:我的代码:

import datetime

import factory
from dateutil import relativedelta

from somewhere.models import Contract

class ContractFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Contract

    start_date = factory.LazyFunction(datetime.date.today)
    first_period_date = factory.SelfAttribute('start_date')
    first_period_end_date = (
        factory.SelfAttribute('first_period_date')
        + relativedelta.relativedelta(months=12)
    )

But in runtime I get the following error:但是在运行时我收到以下错误:

TypeError: unsupported operand type(s) for +: 'SelfAttribute' and 'relativedelta'

So that is apparently not how it's done.所以这显然不是它的完成方式。 But how do I do it?但是我该怎么做呢?

The answer is LazyAttribute ;答案是LazyAttribute SelfAttribute is only helpful for copying a field. SelfAttribute仅对复制字段有帮助。

You should do:你应该做:

class ContractFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Contract

    start_date = factory.LazyFunction(datetime.date.today)
    first_period_date = factory.SelfAttribute('start_date')
    first_period_end_date = factory.LazyAttribute(
        lambda self: self.first_period_date + relativedelta.relativedelta(months=12)
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM