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.

Asked By: A H

||

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

See: https://github.com/FactoryBoy/factory_boy/issues/540

Answered By: A H
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.