Reputation: 717
I'm using Factory Boy in my tests and want to achieve the following:
first_period_end_date
dependent on first_period_date
and add 12 months to it.I'm trying to use SelfAttribute
in combination with relativedelta
but the way I'm currently applying it doesn't work. 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?
Upvotes: 3
Views: 754
Reputation: 3589
The answer is LazyAttribute
; SelfAttribute
is only helpful for copying a field.
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)
)
Upvotes: 4