Skip to content

Utilities

Computed fields

Add computed GraphQL fields by assigning plain resolver functions to __custom_resolvers__. Each function receives the model instance as root, and its name becomes the field name.

from examples.tutorial.business_logic.models import Student


def full_name(root: "Student") -> str:
    # A simple computed field that is exposed via GraphQL.
    return " ".join([root.first_name, root.last_name])


Student.__custom_resolvers__ = [full_name]

Resolvers can return scalars or Strawberry types.

Note

For more details about Strawberry fields: Strawberry.

Auto Foreign Keys

GraftQL can create foreign keys based on DataLoader declarations. For to-one relations, the source field can be referenced to the target field.

router = GraftRouter(engine=engine, auto_foreign_keys=True)

For example:

class Course(GraftModel, table=True):
    id: int | None = Field(primary_key=True, default=None)
    name: str

    students: list["StudentCourse"] = Dl(source="id", target="course_id")

    teacher_id: int
    teacher: "Teacher" = Dl(source="teacher_id", target="id")

Here course.teacher_id gets a foreign key to teacher.id. students is a to-many relationship, so no foreign key is created for it.

Note

If you want behavior different from the router default for a specific Dl, set foreign_key explicitly (e.g. teacher: 'Teacher' = Dl(source='teacher_id', target='id', foreign_key=False)).