You could also use factory.SelfAttribute for fields that depends on others fields.
In your case, LazyAttribute
works fine, and it's quite clear, but if you need to do something a little more complex, SelfAttribute
it's gonna be a better option.
For example, let's say we have an entity called Course with a start_date
and end_date
. Each course has a final test which must be attended after the course starts and before the course ends. Then, model.py should look like this:
class Course(models.Model):
start_date = models.DateTimeField(auto_now_add=False, blank=False)
end_date = models.DateTimeField(auto_now_add=False, blank=False)
class Test(models.Model):
course = models.ForeignKey(
to=Course, blank=False, null=False, on_delete=models.CASCADE
)
date = models.DateField()
Now, let's create our factory.py:
class CourseFactory(DjangoModelFactory):
class Meta:
model = Course
start_date = factory.Faker(
"date_time_this_month", before_now=True, after_now=False, tzinfo=pytz.UTC
)
end_date = factory.Faker(
"date_time_this_month", before_now=False, after_now=True, tzinfo=pytz.UTC
)
class TestFactory(DjangoModelFactory):
class Meta:
model = Test
date = factory.Faker(
"date_between_dates",
date_start=factory.SelfAttribute('..course.start_date'),
date_end=factory.SelfAttribute('..course.end_date')
)
course = factory.SubFactory(CourseFactory)
As you can see in TestFactory
we can reference another field of the object being constructed, or an attribute thereof.