Factory Boy – Reference a field inside a SubFactory
Question:
Say We have the following Django models:
class School:
name: str
class Subject:
name: str
school: School
class Lesson:
school: School
subject: subject
And the following data exists in the tables.
School = ["ABC School"]
School = ["DEF School"]
Subject = ["Maths", "ABC School"]
Subject = ["Maths", "DEF School"]
How can I create a Lesson that grabs the subject of THAT school?
class LessonFactory(DjangoModelFactory):
school = SubFactory(SchoolFactory)
subject = SubFactory(SubjectFactory, school=SelfAttribute('school.id')) # something like this - this doesn't work
class Meta:
model = Lesson
I am currently getting the error, MultipleObjectsReturned: get() returned more than one Subject -- it returned 2!
as it got both school’s Maths.
Answers:
You must use "..school"
, so that it lazily evaluates it.
class LessonFactory(DjangoModelFactory):
school = SubFactory(SchoolFactory)
subject = SubFactory(SubjectFactory, school=SelfAttribute('school'))
class Meta:
model = Lesson
Say We have the following Django models:
class School:
name: str
class Subject:
name: str
school: School
class Lesson:
school: School
subject: subject
And the following data exists in the tables.
School = ["ABC School"]
School = ["DEF School"]
Subject = ["Maths", "ABC School"]
Subject = ["Maths", "DEF School"]
How can I create a Lesson that grabs the subject of THAT school?
class LessonFactory(DjangoModelFactory):
school = SubFactory(SchoolFactory)
subject = SubFactory(SubjectFactory, school=SelfAttribute('school.id')) # something like this - this doesn't work
class Meta:
model = Lesson
I am currently getting the error, MultipleObjectsReturned: get() returned more than one Subject -- it returned 2!
as it got both school’s Maths.
You must use "..school"
, so that it lazily evaluates it.
class LessonFactory(DjangoModelFactory):
school = SubFactory(SchoolFactory)
subject = SubFactory(SubjectFactory, school=SelfAttribute('school'))
class Meta:
model = Lesson