Hi I am trying to make a GraphQL API using FastAPI and Strawberry and could not figure out how to do this. Essentially here is my problem: I have one model (call it Department) that has a one to many relationship with the Employee model, so that department.employees is the list of all employees belonging to that department. The issue I have is that an employee also has a department, so if I split out the types (see below) I have a circular import. How can I resolve this? Thanks.
Employee
import strawberry
from app.models.employee import Employee as EmployeeModel
from app.api.v1.definitions.department import Department
from app.api.v1.definitions.profile import Profile
@strawberry.type
class Employee:
id: str
email: str
instance: strawberry.Private[EmployeeModel]
@strawberry.field
def department(self) -> Department:
return Department.from_instance(self.instance.department)
@strawberry.field
def profile(self) -> Profile:
return Profile.from_instance(self.instance.profile)
@classmethod
def from_instance(cls, instance: EmployeeModel):
return cls(
instance=instance,
id=instance.id,
email=instance.email,
)
Department
import strawberry
from app.models.department import Department as DepartmentModel
@strawberry.type
class Department:
id: int
name: str
@strawberry.field
def employees(self) -> "Employee":
from app.api.v1.definitions.employee import Employee
return [Employee.from_instance(employee) for employee in self.instance.employees]
@classmethod
def from_instance(cls, instance: DepartmentModel):
return cls(
id=instance.id,
name=instance.name,
)
2 Answers
A solution is described in the Lazy Types section of the docs.
1
-
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – From Review
– ouroboros151 mins ago
The answer was:
strawberry.LazyType["Department", "app.api.v1.definitions.department"]
1
-
1
What does this mean? Where did you put this code? I don't know how to combine a resolver and a lazy type. The resolver needs to instantiate the other model and for that it needs a real reference.
– Justin TomanSep 26 at 22:02