Backend-agnostic schema generation for Strawberry GraphQL on top of Django ORM, SQLAlchemy, and Tortoise ORM.
Warning —
strawberry-ormis still in alpha. Expect breaking changes and incomplete APIs while the package stabilizes.
Start here: Installation · Quick start · Choose a backend · How loading works
Before you ship: Security · Production baseline
Feature guide: Defining types · Declaring fields · Filters and ordering · Custom filters and ordering · Grouping and aggregation · Payloads · Mutations · Relay · Async · Contrib
Reference: API reference · Backend options · Public exports · Full example
uv add "strawberry-orm[sqlalchemy]" # or [django] or [tortoise]Or with pip:
pip install "strawberry-orm[sqlalchemy]"Requires Python >=3.12 and strawberry-graphql>=0.311.0.
Minimal blog API: users with published posts only. Assumes SQLAlchemy models User and Post where Post.is_published is a boolean. See Choose a backend to wire session context.
# SQLAlchemy
import strawberry
from strawberry_orm import StrawberryORM, auto
orm = StrawberryORM.for_sqlalchemy(
dialect="postgresql",
session_getter=lambda info: info.context["session"],
)
@orm.type(Post)
class PostType:
id: auto
title: auto
@classmethod
def scope_rows(cls, select, info):
# hide drafts everywhere Post loads
return select.where(Post.is_published.is_(True))
@orm.type(User)
class UserType:
id: auto
name: auto
posts: list[PostType]
@strawberry.type
class Query:
users: list[UserType] = orm.field.eager()
schema = orm.schema(query=Query)
QUERY = "{ users { name posts { title } } }"
# result = schema.execute_sync(QUERY, context_value={"session": session})
# → drafts excluded; only published post titles under each userDrafts are hidden because PostType.scope_rows runs wherever Post rows load — including under users. How loading works explains why, and what you still have to configure yourself.
id: auto and posts: list[PostType] above are the two you need most. Everything else is one of two forms, and the name tells you what the field costs.
eager is a field the optimizer can see through. lazy is your code, run once per parent row.
What separates them is whether your callable needs the parent row. A callable that takes (query, info) doesn't, so the library can fold it into a single query covering every parent. One that takes self does, and that forecloses the folding no matter how capable the backend is.
Usually that means eager costs one query and lazy costs one per parent, but the second half is not a rule: with batch_relations on, Django and SQLAlchemy collapse most lazy relation resolvers into a single query too. What eager guarantees is that no rewrite has to be proven — a scope cannot vary per parent, so it always folds. A lazy resolver whose predicate mentions the parent, slices per parent, or runs its own query gets no such promise. Choosing between eager and lazy has the measured comparison.
On a type — every field on an @orm.type class is one of these:
# SQLAlchemy — see "Reading the examples" for the Django / Tortoise spelling
@orm.type(Post)
class PostType:
# --- eager: one query for every parent --------------------------------------
title: auto # a column
author: UserType # a relation, eager-loaded
body: auto = orm.field.eager( # metadata on a resolved field
permission_classes=[IsAdmin], # field permissions
description="Post body", # forwarded to Strawberry
)
tags: list[TagType] = orm.field.eager(
filters=TagFilter, order=TagOrder, # adds filter/order arguments
) # also: compute=, disable_optimization=
@orm.field.eager # (query, info): narrows the
def comments(select, info) -> list[CommentType]: # relation, named
return select.where(Comment.is_public.is_(True)) # for it
# --- lazy: your resolver, once per parent row -------------------------------
@orm.field.lazy # returns rows: hand back the
def recent(self, info: strawberry.Info) -> list[CommentType]: # query itself,
return select(Comment).where(Comment.post_id == self.id) # unexecuted
@orm.field.lazy(filters=CommentFilter) # ...with filter/order arguments
def searchable(self, info: strawberry.Info) -> list[CommentType]:
return select(Comment).where(Comment.post_id == self.id)
@orm.field.lazy(using=["author"]) # names the relation it reads,
def byline(self, info: strawberry.Info) -> str: # so that loads with the parent
return f"by {self.author.name}" # and costs no extra query
@strawberry.field # plain Strawberry, no ORM
def slug(self, info: strawberry.Info) -> str:
return self.title.lower().replace(" ", "-")
@orm.type(User)
class UserType:
posts: list[PostType] = orm.field.eager( # the inline spelling of
lambda select, info: select.where(Post.is_published.is_(True))
)There is one scope per relation, and it carries that relation's name — comments above scopes Post.comments. A second, differently-filtered view is a lazy resolver.
On the query root — the same forms, minus a parent row:
# SQLAlchemy
@strawberry.type
class Query:
posts: list[PostType] = orm.field.eager() # generated resolver
filtered: list[PostType] = orm.field.eager(filters=PostFilter) # ...with arguments
@orm.field.lazy # your own criteria
def published(self, info: strawberry.Info) -> list[PostType]:
return select(Post).where(Post.is_published.is_(True))Each name has exactly one contract, and the library holds you to it. Hand eager a callable that takes self and it refuses, because a parent row is the one thing an eager field never sees:
byline(self, ...) is not a scope: a scope receives (query, info) and never
sees the parent row. Use orm.field.lazy for a resolver that needs self.
Declaring fields covers how to choose and what else the library checks.
Relay connections use the same two names, but unlike fields the choice is not really yours — it follows from where the connection sits.
# SQLAlchemy
from strawberry_orm.relay import ORMListConnection
@strawberry.type
class Query:
# eager: an entry point over the whole table
posts: ORMListConnection[PostType] = orm.connection.eager()
# ...narrowed, the way a field scope narrows
published: ORMListConnection[PostType] = orm.connection.eager(
scope=lambda select, info: select.where(Post.is_published.is_(True))
)
@orm.type(User)
class UserType:
# lazy: hangs off a parent, so it runs once per user
@orm.connection.lazy(ORMListConnection[PostType])
def posts(self, info: strawberry.Info) -> list[PostType]:
return select(Post).where(Post.author_id == self.id)At a query root, an eager connection covers the whole table. On an @orm.type it is served by the parent's relation instead, and every parent's page is taken in a single query: rows are numbered within each parent by a window function and the low numbers kept, so { users { posts(first: 10) } } costs one query for the pages and one for the counts, however many users there are.
@orm.type(User)
class UserNode(relay.Node):
id: relay.NodeID[int]
posts: ORMListConnection[PostNode] = orm.connection.eager()totalCount is each parent's own total, counted separately rather than read off the page — the page was truncated, so counting it would report the page size.
With no first the page is the one the connection would return anyway — max_results, or default_query_limit when that is smaller — so { users { posts { … } } } is windowed the same way. last without first is not, because where each parent's last page starts depends on its own count, and neither is a connection that selects aggregates or groups, which are taken over each parent's whole relation; those are read one parent at a time, each page still cut in the database. In a union or interface list, such as nodes(ids:), parents are windowed only with others of their own type, since each type's field may be scoped differently.
This works on all three backends. Tortoise has no window expression of its own, so that backend wraps the query it built in SQL that does the numbering; the values you filtered on stay bound rather than pasted into the statement.
What it does need is a column on the related rows tying them to a parent, so a many-to-many is refused when the type is defined — those rows keep the parent key in the association table, leaving the window nothing to partition by. The error points you at orm.connection.lazy, which is the honest spelling for one query per parent.
Note that a connection on a plain @strawberry.type is a root connection wherever it appears — it queries the whole table, because nothing about it knows a parent exists. Put connections over relations on an @orm.type.
Either form gives you cursor pagination, totalCount, and the filter, order, and groupBy arguments generated from the node type — with filters and ordering applied before the slice, so you always page through a correctly sorted set.
A scope= narrows totalCount and aggregates as well as edges. Those are computed from the query rather than from the rows you get back, so a scope that only reached edges would still tell a caller how many rows they are not allowed to see. Connection fields has the rest.
Every backend generates the same schema; they differ in how the session reaches a resolver.
| Backend | Constructor | Session |
|---|---|---|
| Django | StrawberryORM.for_django(...) |
Implicit — Django querysets manage their own connection. |
| SQLAlchemy | StrawberryORM.for_sqlalchemy(dialect=..., session_getter=...) |
Resolved per request from session_getter, info.context["session"], info.context.session, or info.context.get_session(). Sync or async. |
| Tortoise | StrawberryORM.for_tortoise(...) |
Implicit, but async-only — await in resolvers, and see Async usage. |
Sync and async execution both work on Django; a custom async resolver that touches the ORM directly still needs sync_to_async(...).
Every constructor takes the same tuning options — limits, warnings, optimizer switches. They are listed under Backend options; the defaults are safe to start with.
Everything strawberry-orm generates — types, filters, ordering, grouping, mutations — is identical across the three backends. What differs is the query object your own callables receive and return, in exactly one place: whenever you write a scope_rows, a scope=, or a resolver that returns rows.
| Django | Tortoise | SQLAlchemy | |
|---|---|---|---|
| What you receive | QuerySet |
QuerySet |
Select |
| Idiomatic parameter name | queryset |
queryset |
select |
| Narrow rows | queryset.filter(is_published=True) |
queryset.filter(is_published=True) |
select.where(Post.is_published.is_(True)) |
| Exclude rows | queryset.exclude(title="x") |
queryset.exclude(title="x") |
select.where(Post.title != "x") |
| Order | queryset.order_by("name") |
queryset.order_by("name") |
select.order_by(Tag.name) |
| Rows for one parent | Post.objects.filter(author=self) |
Post.filter(author_id=self.id) |
select(Post).where(Post.author_id == self.id) |
| Everything for a model | orm.get_default_queryset(Post) |
orm.get_default_queryset(Post) |
orm.get_default_queryset(Post) |
Each code block below says which backend it is written in. Where only the query expression differs, translate it with this table rather than expecting a different API.
The one rule: the optimizer can only add loads while the query is unexecuted. The first value that materializes ends optimization for everything beneath it.
Returning list(...), .first(), or already-loaded instances from a field means nothing below it can be eager-loaded or scoped. Every behaviour in this chapter follows from that.
Three layers are involved. Your Strawberry types and the client's selection set decide what is asked for; the optimizer mounted by orm.schema() turns that into loads and applies scoping; the ORM backend runs the SQL.
For { users { name posts { title } } }:
Query.usersreturns a User queryset/select.**UserType.scope_rows**may filter it — including joins on related tables, which only affects which users match.- The optimizer walks the selection set and sees
postsunderusers. - To build the prefetch it calls
**PostType.scope_rows**, plus anyscope=onUserType.posts. This is a separate scoping step for Post rows, not a re-run ofUserType.scope_rows. - One batched query loads the users and their scoped posts.
- GraphQL reads
user.postsfrom the prefetched data. No further scoping pass happens on Django or SQLAlchemy for plain annotation relations.
flowchart TD
Q["Query.users"] --> R["Root resolver returns User select/queryset"]
R --> O["Optimizer: apply UserType.scope_rows"]
O --> W["Walk selection set → sees posts"]
W --> P["Build prefetch: PostType.scope_rows + scope=callable"]
P --> SQL["Execute batched SQL"]
SQL --> G["GraphQL serializes instances"]
scope_rows is the row-access boundary for a model: it is handed the query about to run and returns a narrowed one. It pairs with the field-level [orm.field.eager](#the-two-kinds-of-field) — same idea, one on the type, one on a single relation edge.
@orm.type(Post) # Django / Tortoise
class PostType:
id: auto
title: auto
@classmethod
def scope_rows(cls, queryset, info):
return queryset.filter(is_published=True)
@orm.type(Post) # SQLAlchemy
class PostType:
id: auto
title: auto
@classmethod
def scope_rows(cls, select, info):
return select.where(Post.is_published.is_(True))The hook is always called positionally, so name the parameter after whatever your ORM actually hands you:
| Backend | Idiomatic | What arrives |
|---|---|---|
| Django | def scope_rows(cls, queryset, info) |
QuerySet |
| Tortoise | def scope_rows(cls, queryset, info) |
QuerySet |
| SQLAlchemy | def scope_rows(cls, select, info) |
Select |
| Backend-agnostic code | def scope_rows(cls, query, info) |
whichever |
Define it on the @orm.type class for the model being loaded. A nested query runs one hook per model, not one hook for the whole path:
| Query | Root rows | Nested relation |
|---|---|---|
posts { … } |
PostType.scope_rows |
— |
users { posts { … } } |
UserType.scope_rows |
PostType.scope_rows |
posts { author { … } } |
PostType.scope_rows |
UserType.scope_rows |
A row of a subclass of the model (an inherited SQLAlchemy mapping, a Django proxy or multi-table child, a Tortoise model inheriting another) is a row of the model too, and is scoped by the model's scope_rows. Where the model's table holds the row (a Django proxy or multi-table child, a single-table or joined-table SQLAlchemy subclass), that holds however the row is read, as a write asks the model's repo about it: a type over the subclass that defines its own scope_rows adds that scope to the model's, and a row of a subclass of that subclass is held to all three. Where the subclass keeps its rows in a table of its own (a Tortoise model inheriting another, a concrete SQLAlchemy mapping), a type over it that defines its own scope_rows answers for them alone. Any field that hands out such a row as the model's type holds it to both scopes: a lazy or eager field, filtered or not, returning a query, rows it already read or one row; a connection, Strawberry's relay.connection included; a payload; a relation; node(id:); and an interface or union resolving the row to the model's type. On SQLAlchemy, where a polymorphic read of the model returns such a row as the subclass, that type's scope applies to the read as well, so the rows it hides are left out of the model's lists, pages, counts, aggregates, groups and filters through relations.
On SQLAlchemy the hook may return more than a .where(): joins, nested selects and with_loader_criteria hold wherever the rows are read, in counts, aggregates, groups, orders and filters through relations included. A with_loader_criteria applies to every place its entity is read in the statement the scope runs inside. A scope that is more than a .where() on the related table's own columns is loaded onto a relation one statement per relation, by the relation's join key; a relation that does not join on one column (a composite key, a primaryjoin that says more than the key comparison) cannot be loaded that way and raises.
This is the mistake that bites hardest, so it is worth one careful example.
users { posts { … } } looks like a single tree, but the ORM loads it in two steps: User rows first, then Post rows. A filter on the parent type restricts which parents come back. It does not restrict the children — even when that filter joins the child table.
# Django
@orm.type(User)
class UserType:
id: auto
name: auto
posts: list[PostType]
@classmethod
def scope_rows(cls, queryset, info):
return queryset.filter(posts__is_published=True).distinct()
@orm.type(Post)
class PostType:
id: auto
title: auto
# no scope_rowsGiven this data:
| User | Post | is_published |
|---|---|---|
| Alice | "Hello world" | true |
| Alice | "Secret draft" | false |
| Bob | "Bob's only post" | false |
{ users { name posts { title } } } returns:
{
"users": [
{ "name": "Alice", "posts": [{ "title": "Hello world" }, { "title": "Secret draft" }] }
]
}Bob is gone, because the parent filter asked does this user have a published post — and Alice does. But the draft is still there: loading Post rows never consulted UserType.scope_rows again, and PostType has no scope of its own. The join tested existence; it did not filter the child rows.
The fix is to scope the model wherever it loads:
# Django
@orm.type(Post)
class PostType:
id: auto
title: auto
@classmethod
def scope_rows(cls, queryset, info):
return queryset.filter(is_published=True)Now { posts { title } } and { users { posts { title } } } both hide drafts. The same reasoning covers tenant IDs, soft deletes, and permissions: scope every model type a client can reach, and never assume a parent join stands in for a child scope.
| Goal | Where it belongs |
|---|---|
| Hide users with no published posts | UserType.scope_rows, joining on posts |
| Hide draft posts under every user | PostType.scope_rows |
| Hide drafts on one relation edge only | scope= on UserType.posts |
| Both parent and child | Both hooks — they are independent |
How a field is written decides what scoping it gets.
| Field | Scoping |
|---|---|
users: list[UserType] = orm.field.eager() |
Optimizer + UserType.scope_rows |
posts: list[PostType] (annotation) |
Related type's scope_rows, loaded by prefetch |
orm.field.eager(…) with a scope |
Composes after the related type's scope_rows |
@orm.field.lazy returning a query object |
Optimizer + that type's scope_rows — see Root custom query |
@orm.field.lazy returning self.author |
As written; scoping only via prefetch |
@strawberry.field, fully custom |
You own scoping and auth |
| A resolver returning instances | Nested relations scoped and eager-loaded — see Rows a resolver already fetched |
The first four rows are all orm.field, which has two named forms that differ in what they cost — see The two kinds of field.
Type-level and field-level scopes compose in that order — scope_rows first, then scope= — and both run before SQL executes.
Relation scoping does not depend on the optimizer. When the optimizer runs it applies the scope once while building the eager load; when it does not, the scope is applied again as each parent's relation is read. Either way the rows are scoped — the difference is how many queries it takes. The root field is the exception: scope_rows on a root query object is applied by the optimizer, so build with orm.schema().
A root Query field returns rows directly rather than through a relation. With orm.schema(), returning an unexecuted select or queryset still engages the optimizer: your filter composes with UserType.scope_rows, and nested fields still get their own type's hook at prefetch time.
# SQLAlchemy
@strawberry.type
class Query:
@orm.field.lazy
def active_users(self, info: strawberry.Info) -> list[UserType]:
return select(User).where(User.is_active.is_(True)) # ✓ query object
# return session.scalars(...).all() # ✗ materializedUse scope_rows when the same rule applies everywhere the model loads, and a custom root resolver when the criteria belong to that one entry point. See List Fields for a comparison.
A resolver that returns rows rather than a query object gives the optimizer nothing to add eager loads to. It handles that case anyway: the rows are all it needs, so it loads their relations onto them.
# Django
@strawberry.field
def create_post(self, info: strawberry.Info, ...) -> PostType:
return Post.objects.create(...) # relations below still eager-loadedThis reaches rows nested inside a wrapper too. A payload's data is a resolved field in its own right, so the rows arrive with exactly the selection that describes them.
Relations are loaded onto the rows you returned, so a value you just set in memory is never overwritten by a re-read of the database — the mutation above reports the title it wrote, not the one in the database.
orm.optimize — the manual form
Rows that never pass through a resolver's return value are out of reach, and for those there is orm.optimize(data, info). It takes a query object, a model instance, or a list (lists nested in it included), and returns anything else untouched. Instances are checked against their type's scope_rows before anything is loaded onto them, and what comes back leaves out the rows it rejects (None for a single rejected instance), so use what it returns.
# Django
rows = list(Post.objects.filter(...))
rows = orm.optimize(rows, info)Calling it on rows the optimizer already prepared costs nothing. at="data" re-roots the selection when the rows sit below the resolved field; at also takes a sequence for a deeper path and matches either camelCase or snake_case. Getting it wrong is not an error — nothing is eager-loaded and the rows come back as they would have anyway.
Build schemas with orm.schema(). The optimizer is enabled by default: it executes query objects, eager-loads relations from the selection set, applies field hints, and honours scope_rows. On Django and SQLAlchemy nested scoping depends on it, so this is not an optional performance tweak.
schema = orm.schema(query=Query, mutation=Mutation)
schema = orm.schema(query=Query, extensions=[MyCustomExtension()])
schema = orm.schema(query=Query, optimizer=False) # opt out per schema
orm = StrawberryORM.for_sqlalchemy(enable_optimizer=False, …) # or globallyschema_class= builds your own strawberry.Schema subclass instead, with the same extensions mounted.
A schema built with strawberry.Schema directly gets scope_rows only from extensions=[orm.optimizer_extension()]. Without it, nothing holds a resolver's rows to scope, so a row of an @orm.type is refused as it is served (Cannot serve PostNode: no extension of this schema holds its rows to scope_rows. …), and so is a relay.connection over rows. It is not checked as it builds: see Common mistakes for what else it skips.
Relay's node() fields work in every schema orm.schema() builds, tagged or with cut inputs, and one Query can go into any number of them; Strawberry's own strawberry.Schema cannot build a node() field twice. Build a plain strawberry.Schema from the same Query only after orm.schema(): once Strawberry has set up the field, orm.schema() raises Query fields cannot be resolved.
A schema has one type per name. The library names the types it generates after the model, node type, resolver or name= they are built from (PostFilter, PostNodeConnection, CreatePostPayload), and Strawberry publishes whichever of two classes of one name it meets first, for both. orm.schema() refuses a schema in which the two differ: orm.filter(Post, include=["title"]) on one type and orm.filter(Post) on another, orm.filter(User) built before and again after the filter of a model it relates to (or an order or group-by, likewise), two orm.ref(Post) offering different operations, two node types over one model that both group. The error names the field that would be served the other type and what differs, as in Query.staff takes a PostConnection other than the one the schema publishes: its edges holds StaffPostEdge, not PublicPostEdge. Build one for both, or name them apart: with name= where the builder takes one, and for a grouped connection, with a connection type of its own (see Grouping and aggregation). Two built alike are published once. A filter or order built twice for types that show different columns is refused as well, since each is cut to what its own types show. A schema built with strawberry.Schema directly is not checked.
When several GraphQL APIs share types, tag what belongs to only some of them, and build one schema per API from the same classes. A field without tags is in every schema. A tagged field is in each schema built for one of its tags.
from strawberry_orm import tags
@orm.type(User)
class UserType:
id: auto
name: auto # every schema
email: auto = orm.field.eager(tags="internal")
posts: list[PostType] = orm.field.eager(tags=["internal", "partner"])
@orm.field.computed(tags="partner")
def handle(self, info: strawberry.Info) -> str: ...
@strawberry.type
class Query:
users: list[UserType] = orm.field.eager()
audit_log: ORMListConnection[AuditNode] = orm.connection.eager(tags="internal")
@strawberry.field(metadata=tags("internal"))
def health(self, verbose: Annotated[bool, strawberry.argument(metadata=tags("internal"))] = False) -> str: ...
@strawberry.type
class Mutation:
@strawberry.mutation(metadata=tags("internal"))
def purge_cache(self) -> bool: ...
public = orm.schema(query=Query, mutation=Mutation, tags="public")
internal = orm.schema(query=Query, mutation=Mutation, tags="internal")
partner = orm.schema(query=Query, tags="partner")Every ORM helper takes tags=: orm.field.eager / .lazy / .computed, orm.connection.*, orm.node and orm.payload.*. Anything declared with Strawberry itself takes metadata=tags(...): fields, mutations, arguments and input fields. On an @orm.type, a strawberry.field(metadata=tags(...)) that sets nothing else only tags the attribute. The library still resolves the column or relation underneath.
A tag on an argument holds wherever the argument ends up: in the input that input_mutation=True or InputMutationExtension builds from it, and after any field extension adds, rebuilds or renames arguments. Fields declared in @orm.filter_type, @orm.order_type or @orm.group_type keep their tags. A filter, order or group-by input is cut to the fields of the types the tagged schema actually serves, counted after field extensions have added their arguments, so a filter an extension adds to a field offers no column that field's type hides.
What a schema built with tags= keeps:
- Fields, arguments and input fields that are untagged or carry one of its tags.
- Only the types something it keeps still reaches.
PostTypeabove is left out of the public schema. - Without
tags=,orm.schema()keeps everything.
Building the schema fails, naming the field, when a tag would leave a schema that cannot work:
- A hidden argument or input field without a default, including one a field extension adds, because no client of that schema could ever supply it. A hidden one with a default takes the default.
- A type whose every field is hidden. Tag the fields that return it instead.
Tags are field metadata stored under strawberry_orm.TAGS_KEY, next to any metadata= you pass. Filter, order and group-by inputs are cut to what each schema serves, as above. Mutation projections are built field by field by the library, so build a separately named one per schema where they should differ.
The optimizer follows the selection set, so a relation the client asks for is prefetched without you saying anything. Two cases it cannot see:
@orm.type(Post)
class PostType:
# a resolver reads a relation the query never selected
@orm.field.lazy(using=["author"])
def byline(self, info: strawberry.Info) -> str:
return f"by {self.author.name}"
@orm.type(User)
class UserType:
# only some of the related rows should load
posts: list[PostType] = orm.field.eager(scope=lambda qs, info: qs.filter(is_published=True))using= answers what to load, scope= answers which rows. Both run while the prefetch is built, so using=["author"] becomes select_related on Django and prefetch_related on Tortoise, where a query's own prefetches run first and the scoped ones after them. On SQLAlchemy a scoped relation is read by a statement of its own, keyed by the parents' join columns, and an unscoped one through loader options. That is one query per relation, not one per row.
A using= entry can walk several relations. "author.posts" loads each post's author and that author's posts; Django's "author__posts" spelling means the same:
@orm.type(Post)
class PostType:
@orm.field.lazy(using=["comments.author"])
def commenters(self, info: strawberry.Info) -> list[str]:
return [comment.author.name for comment in self.comments]Rows loaded through using= are scoped exactly as if the client had selected them: each hop applies the related type's scope_rows and any scope= on the field of that name. When the schema does not show which type a hop's rows are read as (the path walks a relation the type has no field for), every type over that model contributes its scope= on the next relation, so the hop loads only rows all of them allow. A row the resolver may not see reads as absent, None for a to-one relation and missing from a list. On Django a hidden row behind a non-nullable foreign key raises RelatedObjectDoesNotExist instead, because that is how Django's descriptor reports an empty cache, so read it with getattr(self, "author", None). When the client also selects a relation on the path, the two share one load, and a relation the client filters or orders still loads the using= paths below it under their scopes. Before a using= resolver runs, each relation on its paths is checked to hold exactly the rows this execution loaded under that hop's scopes. A relation the app, the identity map, another request or another field filled is read again under them first, at the cost of a query. This holds for rows the app keeps between requests, in a module-level cache say, for roots the optimizer cannot plan, such as an aliased() or with_polymorphic() statement or a plain list, and for the deprecated orm.field(using=…), orm.field.auto(using=…) and orm.field.scoped(using=…) as much as for orm.field.lazy(using=…). Under an interface or a union, each type the rows may be read as plans its own using= paths.
A scope= callable receives (qs, info) and never the parent instance, which is exactly what lets the optimizer hoist it. When the query really does depend on the parent row, write a resolver instead. A scope narrows rows with conditions. One that limits or offsets them (.limit(2), qs[:2], .offset(1), .fetch(2)) is refused on every read, the root list included: the library applies it under the client's filter and order, to every parent of a relation at once, and inside counts, groups and filters through relations, where the limit would count other rows. A scope allowing no rows (.limit(0), qs[:0], .none()) hides every row. A limit the field's own resolver sets is kept. The same holds for scope_rows.
Names are validated when the type is defined, hop by hop, so a typo fails immediately rather than silently doing nothing:
ValueError: PostType.byline: Post has no relation 'athor'. Did you mean 'author'?
ValueError: PostType.byline: User has no relation 'post' (in using='author.post'). Did you mean 'posts'?
See Declaring fields for the full set of forms and arguments.
A resolver on a relation field runs once per parent row, so { users { posts { … } } } over 250 users is 251 statements. When the resolver returns an unexecuted query, the optimizer rewrites that into one statement per query shape:
# Django
@orm.type(User)
class UserType:
name: auto
@strawberry.field
def posts(self, info: strawberry.Info) -> list[PostType]:
return Post.objects.filter(author=self, is_published=True)| Parents | Without batching | With batching |
|---|---|---|
| 3 | 5 statements | 3 |
| 53 | 55 statements | 3 |
| 253 | 255 statements | 3 |
Parents are already in memory and building a queryset touches no database, so the resolver runs up front for every sibling parent of the same GraphQL type, the parent predicate is reflected out of each query, and the remainders are grouped. Branching therefore costs one statement per branch rather than one per row:
# Django
if self.is_admin:
return Post.objects.filter(author=self)
return Post.objects.filter(author=self, is_published=True)Batched queries take the same optimizer path as per-row ones, so the child type's scope_rows and scope= still apply. Turn it off with batch_relations=False.
When batching declines to rewrite
It falls back to per-row resolution — never to wrong rows — when:
- the parent key sits inside an
ORarm, or is reached through a join - the query is sliced, since a per-parent
LIMITneeds a window function - the resolver executed its own query:
list(...),.first(),.count() - the parent is in a union or interface list and its type cannot be told ahead: an
is_type_ofof your own decides it, or it was returned withoutstrawberry.castwhere two types share its model - the backend is Tortoise, whose query internals are not stable to introspect
- on SQLAlchemy, the statement carries an option with nothing to compare it by, such as a
UserDefinedOption - the query holds state it cannot compare: a
QuerySetsubclass overriding its methods, a custom iterable, rows already read, an attribute set on the queryset or statement, aSelectsubclass, or a parameter that is not a plain value
A resolver embedding a per-parent literal such as created_at__gte=self.joined_at stays correct but forms one group per distinct value, so it may not reduce the count. Siblings batch together only when their queries are identical apart from the parent key: on Django, prefetch lookups, values(), the model or proxy, fetch_mode() and the database count toward the shape. On SQLAlchemy, execution options and loader options count toward the shape, since a do_orm_execute hook can read them, and so do the mapped class and compile options.
Edge cases and diagnostics
Tracing hook order. Add print(..., flush=True) inside your hooks:
# Django
@classmethod
def scope_rows(cls, queryset, info):
print("SCOPE:PostType.scope_rows", flush=True)
return queryset.filter(is_published=True)
posts: list[PostType] = orm.field.eager(
lambda qs, info: (
print("SCOPE:UserType.posts.load", flush=True) or qs.filter(title != "GraphQL Guide")
)
)For { users { name posts { title } } } the order is always PostType.scope_rows then UserType.posts.load. With a plain annotation and no scope=, only the first line appears. When the relation was eager-loaded, the hooks run once for the whole batch; when it was not, they run again for each parent as the relation is read. Either way they run. The repo asserts this by patching print — see tests/backends/*/test_query_scoping_hook_order.py.
Fragments. The optimizer walks inline fragments (... on PostType) and named fragment spreads, so relations inside them are prefetched normally, and leaves out what @skip and @include leave out. Each fragment and selection is planned once per operation for each model and type it is read as, and shared wherever it is spread; a relation selected several times, under aliases or from different fragments, is planned once with all of its selections. An operation may plan at most 200 relation loads plus 8 for each field its document writes out (each fragment's once). One that spreads fragments under several relations many levels deep can need more, and is refused before anything is read (This operation plans more relation loads than its size allows: …).
Field permissions. orm.field.eager(permission_classes=[...]) — see Declaring fields.
If nested rows come back unscoped, check that
scope_rowsexists on every exposed type. Scoping does not depend on the optimizer: a resolver returning a list is slower than one returning a query object, but it is not less scoped. See Security.
strawberry-orm has safety-focused defaults, but schema design determines what clients can read and write.
orm.input(),orm.filter(),orm.order()and node mutation inputs exclude sensitive-looking fields and relations (password_hash,api_key,totp_seed,reset_code,security_answer,is_admin,roles,groups, etc.), and attributes private to the model (a name starting with_), unless you name them. A name is read by its words, split at underscores, digits and case changes, and a run-together name such asawssecretaccesskeyis split into the words it is made of. Soaes_keyanddb_passare left out, andsecretaryandhashtagstay in. The names are a backstop, not a list of what is private: a session ID, a date of birth or a card'spanis ordinary data to many apps and stays in, soexclude=what a type must not offerorm.input()andorm.partial()leave out the foreign key column a link sets (author_id), and both columns of a DjangoGenericForeignKey, unlessinclude=names it, since writing it as a value skips the related repo'sscope_queryandcan_link- String regex filters are disabled by default, and Tortoise offers none. Once enabled, a pattern is held to 100 characters. One that can backtrack for more than quadratic time, or that Python's
recannot read as written, is refused. A filter argument or a request may use at most 3 regex lookups, and the regex is given only values of at most 256 characters. See Filter shape - Text lookups (
contains,startsWith,endsWithand theiriforms) may hold at most 1,000 characters across a filter argument and across a request - The values a filter binds may hold at most 100,000 characters across a filter argument and across a request, each reference to a variable counted, so a long value sent once and referenced from many places is measured as often as it is bound
- Filter depth is capped, and so are the branches and the listed values of a whole filter argument, every reference to a variable included
- A connection reads at most one page, and so does each group's
items:first,lastandbeforealone are held tomax_results(anddefault_query_limitwhen smaller), and a cursor before the first row is refused — see Connection fields orderandgroupBylists, the groups a connection answers with, and the related rows in anobjects:group key are capped (max_order_entries,max_group_by_entries,max_groups,max_group_key_rows)- On every backend, any error the ORM or its driver raises while building or running a statement, whatever its type, reaches the client as
Invalid filter expressionfor a read, asThe database refused the writefor a writeorm.apply_upsert()ororm.apply_ref_list()makes, or asDatabase connection failedwhen the connection fails, never with its SQL, parameters, tables, columns, model classes or values. That covers an error raised while ascope_rowsorscope=builds its query, a value the ORM or a field's validator refuses for its column (a malformed UUID, a string for a duration), SQLAlchemy's unit of work refusing a flush, and an integer the driver cannot bind. Either way the original is the exception's__cause__, for your logs. An error raised in the library's own code, such as a limit refusing a filter, keeps its message, and quotes at most 40 characters of any value it names. An SQLAlchemy create that takes the key of a row its session already holds is refused asThe database refused the writetoo. Values a client sends are kept out of Python's warnings, whose registry the process keeps forever: with time zones on, a naive datetime or time a client sends is read in the default time zone before Django or Tortoise sees it, as they would read it - A row
orm.apply_upsert()ororm.apply_ref_list()updates is saved with the change the write decided on and nothing more, so a column another request changed after the write read the row keeps that change, and a row deleted in between stays deleted — see A write saves what it set orm.ref()provides explicitunlinkanddeleteoperations — both opt-in viaunlink=Trueanddelete=True- When you use
orm.schema()(optimizer enabled by default), nested relation loads honor each type'sscope_rows— but only for types where you define it (the ORM warns at type registration whenscope_rowsis missing). On SQLAlchemy, a relation the mapper loads by itself (lazy="joined"or"selectin") where a query does not select it is loaded unscoped, so a row that query also reaches by a path that does select it has that relation checked against the scope when it is read, not trusted - Filters, ordering, group-by and aggregates cover only the columns and relations the GraphQL types they serve show: the types they are attached to, the type an
orm.fieldororm.connectiontaking them returns, and throughobject:, the type the relation returns, a plain@strawberry.typeincluded. A@strawberry.fieldresolver of your own that takes one is not counted, since what it returns need not be the rows it filtered: the input still covers the types it is attached to, so a filter attached to a staff type and handed to a resolver returning a plainUserCard { name }can still filter on the staff type'semail. Give such a resolver an input of its own, attached to a type that shows only what it returns. A column those types leave out, or show through a resolver of your own,on=,compute=, permission classes or fieldextensions=(aPermissionExtension, say), cannot be filtered on, sorted by, grouped by, or read throughmin/max— any of which would reveal it.orm.schema()works this out for the types each schema reaches, and a kept field carries the tags of the type field it mirrors, so a tagged schema drops both together - Filtering through a relation (
filter: { object: { author: … } }) is restricted to the rows the related type'sscope_rowsand the relation'sscope=allow, so a filter cannot confirm values on rows the caller cannot read. Thescope=is the one on the type the field returns; past anobject:hop, where that type is not known, every type over the model contributes itsscope=. Through a to-many relation,object:asks whether some readable related row matches, andnot:negates that whole question - A type's
scope_rows, and a relation's scope, are written into the statement before the client's filter, so a database that evaluates conditions in the order written runs a costly condition only on rows the caller can read, and its running time says nothing of the others - On SQLAlchemy, a relation whose
primaryjoinorsecondaryjoinsays more than its key columns (open_tasks, withdone == False) is left out ofgroupBykeys andobjects:orders, and a connection over it, or anon=view of it, is refused when its type is declared, since each would rebuild the join from its keys and reach rows the relation does not list - Ordering through a relation into a scoped type is rejected when
orm.schema()builds, because the resulting sequence would itself rank hidden rows — see Ordering into a scoped type - Connection
aggregatesandgroupsare computed with the type'sscope_rowsapplied, so counts and sums cover only readable rows
| Concern | Library | You |
|---|---|---|
| Authentication | — | middleware, info.context, permission classes |
| Row access | scope_rows per exposed type |
define on every model type clients can reach — parent scoping does not flow to children |
| Column exposure | filters, ordering, group-by and aggregates follow the type's fields; write inputs leave out what exclude= hides |
exclude=[...] on @orm.type for a column no input may write or match on, or orm.field.eager(permission_classes=…) — write inputs follow the model |
| Query size | page size, order/groupBy length, group count |
default_query_limit for root lists; a query budget (Strawberry's MaxAliasesLimiter, MaxTokensLimiter, QueryDepthLimiter) |
| Mutations | — | auth in resolvers; authorize callback on apply_ref_list |
| Write access | a repo's scope_query and can_* hooks on every generated write |
a repo per writable model whose scope_query mirrors its scope_rows — writes do not apply scope_rows |
| Custom resolvers | — | same as hand-written DB access — you own scoping |
Strawberry's QueryDepthLimiter and MaxAliasesLimiter walk a fragment again wherever it is spread, so an operation of a few hundred tokens whose fragments each spread the next several times can hold one for seconds before anything runs (QueryDepthLimiter took 6 seconds over five levels of 32 spreads on strawberry-graphql 0.341.2). The optimizer plans each fragment once per operation and refuses an operation that would plan more loads than its size allows, but the limiters run first; until they do the same, refuse operations with more fragment spreads than your clients send, with a validation rule of your own.
scope_rows narrows what a caller reads. orm.apply_upsert() and orm.apply_ref_list() find the rows they write through the model's repo instead, so a model clients can write needs an AbstractRepo whose scope_query narrows the query as its scope_rows does. Without one, a caller can update, link or re-point any row by its ID: taking another user's post into their own posts list makes it theirs, and readable. An upsert's match on where answers too, telling a caller whether a hidden row with those values exists. A scope_query narrows rows with conditions. One that adds a limit, offset or fetch (.limit(2), qs[:2], .offset(1)) is refused wherever a write looks a row up, because the lookup takes its own limit, and one allowing no rows (.limit(0), qs[:0], .none()) hides every row: the rule scope_rows and scope= follow. A subclass of the model (an inherited SQLAlchemy mapping, a Django proxy or multi-table child) with no repo of its own is written through the model's. A subclass row with a repo of its own is written through that one, even when the write reaches it through the base: a row a read hands back as the subclass is that subclass's, and where it reads as a base row (a Django multi-table child, or a SQLAlchemy joined-table subclass mapped without polymorphic_on) the write looks for it in each such subclass's table and takes the deepest one holding it. A row two unrelated subclasses both hold is one no single repo can answer for, so a write treats it as missing, and re-pointing a link off one is refused. A Django proxy keeps its rows in its base's table with nothing to tell them apart, so its repo governs only inputs built on the proxy; reached through the base, a proxy's row is the base's. All of this holds for one repo class registered for both models: its self.model is the row's own model when it answers for the row. A row is a row of each model it inherits, so the base keeps its say: the row must be one each of their repos' scope_query shows, and authorize=, a MutationPolicy and the repos' can_* are asked about every model the row belongs to (the input's model and its bases, then the row's own model and its bases), each repo once. So the base's repo is asked its can_* too, and a check keyed on Doc refuses a Contract row. An upsert's match on where leaves out a row any of those repos' scope_query hides, a base's as well as a subclass's, so it cannot count one.
A unique constraint compares every row in the table, the ones the caller cannot read included. Creating a row with an email another tenant's user already has comes back as The database refused the write, and any other email succeeds, so a caller can test whether a value is taken anywhere. Where that is sensitive, make the constraint per tenant (unique on tenant_id and email together), so the values it compares are only the tenant's own.
A generated create, update or where input is built from the model, not from a type, so it offers every column exclude= does not hide, including one the type simply leaves undeclared. Writing such a column is the input's purpose, but matching on it is a read: with where: True, a caller who can reach a row through the repo can send salary in where and learn from match or no match whether the row's salary is that value, though no filter offers it. List the fields _meta.create, _meta.update and _meta.upsert.where may use, or exclude= the column on the type, which leaves it out of every generated input.
A repo's on_before_create and on_before_update run before can_create and can_update, so a hook can fill in what the check reads, such as the caller's tenant. They are handed the client's data before anything has approved it: keep side effects, such as sending mail, for on_after_*, which run once the whole write has passed every check and the database has accepted it (SQLAlchemy flushes the session first, and Django checks the deferred foreign keys of the tables written), in the order the rows were written, so a refusal anywhere in it runs none of them. Update data, as a hook returns it, cannot set a key or parent link: saved, it would write the row that key names, so it raises UpsertValidationError. A commit can still fail after them, from a serialization failure or a constraint your app defers itself, so a hook that must not run for a write that never lands belongs after your commit. Nothing caps how many items a write's lists carry, and _meta.maxVisits is unbounded unless you set it, so bound the size of a request (Strawberry's MaxTokensLimiter, or your server's body limit) and set maxVisits on a projection that recurses.
orm.apply_upsert() and orm.apply_ref_list() read each row they update, ask authorize and the repos about the change, and then save it, and another request can change or delete the row in between. The save writes the fields the input set and those on_before_update returned, even one set to the value it was read with; every column assigned on the row since it was read, by a hook, on_match or an override of _save before it calls super(); and each column the ORM stamps on a save (auto_now on Django and Tortoise, onupdate on SQLAlchemy). It writes nothing else, so every other column keeps what the database holds by then. A row no longer there is not inserted again: a write that would set a column of it is refused as The database refused the write, and nothing it did is kept. Linking a row into a reverse foreign key list, or unlinking it, writes only that key. SQLAlchemy's unit of work saved rows this way already. On Django the save names its update_fields, so a model save() override or a pre_save receiver that sets a column of its own has to add it to update_fields, as Django's documentation advises, for it to be saved, and signal receivers see update_fields set. A value changed in place, such as a key added to a JSON field's dict, does not count as assigned: assign a new value, or return it from on_before_update. A row your own code reads and hands to a repo's _save is saved as the ORM saves it.
The checks are not run again when the row is saved, and nothing locks it in between. A column a check decided on that another request changes in that window, such as a scope column like tenant_id or the foreign key a link moves, is not looked at again: the columns the write sets land on the row as it is by then, and a link or unlink writes its key whatever the key held by then (Django unlinks only from the parent the write asked about). Where that window matters, have your repo lock the rows it reads for a write (select_for_update() on Django and Tortoise, with_for_update() on SQLAlchemy) on a database with row locks.
Filtering through a relation can be made safe by restricting the join — hidden rows simply never match. Ordering cannot: every row still has to stand somewhere in the sequence, and its position leaks the hidden sort key. If visible authors bracket a hidden one alphabetically, the caller has learned something about a row they cannot read.
So if an order input can sort through a relation whose rows something hides, orm.schema() refuses to build. That is the same set of restrictions filtering through the relation applies: the target type's scope_rows, the scope_rows of a subclass a read of the target hands back as itself (a polymorphic SQLAlchemy mapping), and a scope= on the relation field of any type over the model:
Cannot order by Post.author: User is scoped by scope_rows, so ordering would
rank rows the caller cannot read. Order by a column on Post, or pass
allow_scoped_ordering=['author'] when building the order type for Post if every
readable Post is guaranteed to have a readable User.
The reason after the colon names which restriction it is, such as Post.author has a scope= or Document has subclasses scoped by their own types' scope_rows (Contract). A schema built with strawberry.Schema directly skips the build check, and the same order is refused when a query sends it; the client is told only Cannot order by author: its rows are scoped, so ordering by them would rank rows the caller cannot read., and the message above is the error's __cause__.
Three ways forward:
# 1. Sort by a column on the row itself (also faster — no join)
@orm.order_type(Post)
class PostOrder:
title: auto
author_name: auto # denormalized onto Post
# 2. Opt in, per relation, when the scope is a partition your rows can't cross
# (e.g. tenancy: every readable Post already has a readable author)
@orm.order_type(Post, allow_scoped_ordering=["author"])
class PostOrder:
title: auto
author: auto
# 3. Take ownership with a custom order field — the library does not second-guess
# hand-written callbacks, so the scoping decision is yours
@orm.order_type(Post)
class PostOrder:
title: auto
@order_field
def by_author(self, query, value, info): ...allow_scoped_ordering only lifts the ordering restriction for the relations you name, on that one order input. scope_rows keeps scoping reads and filter traversal exactly as before, and another order input over the same model is unaffected. Naming a relation the order input cannot sort through is an error, so typos fail loudly.
An objects: order is not checked. The set it sorts by leaves out the rows the caller cannot see, so a row's place shows no more than its relation field does. The same order input still offers object: through that relation, and that is checked.
Pass allow_scoped_ordering=True to allow every relation that order input can sort through. Naming them one by one is the better habit — it keeps the decision visible per relation — but the names only exist once the type is built, so a schema generating its order inputs in a loop cannot list them. Reach for it when you have decided the rule holds across the model: every readable parent implies a readable child.
If you build with strawberry.Schema directly instead of orm.schema(), the build-time check does not run; the offending query is rejected at execution instead.
Each one links to the mechanics.
| Mistake | Why it leaks | Where |
|---|---|---|
Parent scope_rows used to scope children, including via a join like posts__is_published=True |
Tests existence of a child, does not filter children | Parent scoping does not flow to children |
A relation resolver that materializes — list(self.posts.all()), .first() |
Skips scope_rows and the optimizer entirely |
Resolver kinds |
strawberry.Schema instead of orm.schema() |
Without orm.optimizer_extension() no scope_rows runs, so it serves no row of an @orm.type; with it, inputs cover every column, Strawberry pages its connections, and two generated types of one name go unchecked |
[orm.schema()](#ormschema) |
| A root resolver returning instances | Optimizer cannot prefetch or scope anything below | Root custom query |
scope_rows that ignores info.context |
Hardcoded tenant or user filters leak across requests | [scope_rows](#scope_rows--one-model-one-type) |
@orm.type exposing secrets through auto |
Output types do not hide sensitive columns for you | Defining Types |
# Django; translate the query expressions with "Reading the examples"
return list(self.posts.all()) # ✗ materialized: no scope_rows, no optimizer
return self.posts.all() # ✓ scoped, and batched into one statement
schema = strawberry.Schema(query=Query) # ✗ no scope_rows: every row is refused
schema = orm.schema(query=Query) # ✓ optimizer and scoping active
return list(User.objects.all()) # ✗ optimizer skipped for everything below
return orm.get_default_queryset(User) # ✓ still a query object
return queryset.filter(tenant_id=1) # ✗ same tenant always
return queryset.filter(tenant_id=info.context["tenant_id"]) # ✓ per-request scopeBetter than a filtering resolver is no resolver at all, so the relation stays a single prefetch:
posts: list[PostType] = orm.field.eager(lambda qs, info: qs.filter(is_published=True))And keep secrets off output types explicitly:
@orm.type(User, exclude=["password_hash", "api_key"])
class UserType:
id: auto
name: autoorm = StrawberryORM.for_sqlalchemy(
dialect="postgresql",
session_getter=lambda info: info.context["session"],
default_query_limit=100,
max_filter_depth=8,
max_filter_branches=25,
max_in_list_size=200,
max_filter_text_length=1000,
max_filter_value_length=100_000,
max_regex_filters=3,
max_regex_text_length=256,
max_order_entries=5,
max_group_by_entries=3,
max_groups=100,
max_group_key_rows=50,
)
schema = orm.schema(query=Query) # optimizer on by defaultdefault_query_limit caps every connection page, every generated root list, and every root list an @orm.field.eager() or orm.field.lazy(filters=…, order=…) resolver returns as a query, after its filter, order and scope_rows. A nested relation list (posts: list[PostType] under each user) is not limited: it returns all of a parent's visible rows, so bound it from the root, or make it a connection. Nor is the query a resolver of your own returns on a field with no generated filter or order, such as a plain orm.field.lazy.
Relation fields load the related model; scoping is per type — see How loading works.
from strawberry_orm import auto
@orm.type(User)
class UserType:
id: auto
name: auto
email: autoauto is an alias for strawberry.auto. The backend inspects the model and resolves the Python type for each field.
Keyword arguments: include, exclude, name, filters, order. include= cannot take a field off the class, so it has to list every field the class declares or inherits, other than one with a resolver of its own; leaving one out raises ValueError.
@orm.type(User, exclude=["password_hash", "api_key"], name="PublicUser")
class PublicUserType:
id: auto
name: auto
email: autoReference other generated types directly. The backend auto-generates resolvers for relationship fields:
@orm.type(Post)
class PostType:
id: auto
title: auto
tags: list[TagType]If the nested type carries filters and/or order, list relations expose those arguments automatically.
Generate input types from model metadata:
CreateUserInput = orm.input(User, include=["name", "email"])
UpdateUserInput = orm.partial(User, include=["name", "email"])input() and partial() share the same signature: include, exclude, exclude_pk (default True), name. Fields are optional (defaulting to strawberry.UNSET), skip relations, leave out every column that names a row (the primary key, and the keys and parent links a Django multi-table or SQLAlchemy joined-table child inherits, such as id, doc_ptr, doc_ptr_id, and a one-to-one key), which include= does not bring back and exclude_pk=False does, and exclude sensitive-looking fields, and attributes whose name starts with _, unless explicitly included.
They also leave out the foreign key column a link sets, such as author_id, and both columns of a Django GenericForeignKey, unless include= names it. As a plain value it links whichever row it names: orm.apply_ref_list() writes it without asking the related repo's scope_query or can_link, as a link written through the relation would. Name it only where your resolver checks the row it points at, or use a node mutation input, whose links go through the related repo.
A field is either declared — the library resolves it — or written by you. Which one you pick decides when your code runs and what it can see. A strawberry.field(...) without a resolver on a relation only adds its options to the field the library builds; give it a resolver, or use orm.field.lazy, to resolve the relation yourself. A plain default on a relation (author: UserType | None = None) is refused, since the library resolves the relation under its scopes and the default would never be read.
orm.field has two named forms. The name tells you what the field costs, which follows from whether your code needs the parent row:
| You supply | Runs | Receives | |
|---|---|---|---|
orm.field.eager() |
metadata | once, while the prefetch is built | — |
orm.field.eager(...) |
a narrowing | once, while the prefetch is built | (query, info) |
orm.field.lazy |
the resolver | once per parent row | (self, info) |
orm.field.lazy(using=[...]) |
the resolver, and what it reads | once per parent row | (self, info) |
eager never sees a parent row. That absence is the point: with no parent to look at, the optimizer folds the field into a single prefetch covering every parent at once. It also makes a field-level scope symmetric with scope_rows(cls, query, info).
using= belongs on lazy and nowhere else. It exists to disclose relations the optimizer cannot see being read, and only a resolver hides anything — an eager field is either written by the library from the selection set or handed back by your scope as a query the ORM reads in full. A lazy(using=[...]) field still runs once per row, but the relations it names load with the parent, so those reads usually cost nothing. A relation on its paths that this execution did not load under its scopes, filled by your own code, a mapper's eager load or another request sharing the rows, is read again before the resolver runs, at the cost of a query. On Django from async code and on SQLAlchemy with offload_sync_session, such resolvers run on the ORM's worker thread. A resolver raises RuntimeError if other loads keep replacing its relations, or, on SQLAlchemy, if a relation holds unflushed changes.
# Django
@orm.type(User)
class UserType:
id: auto
name: auto
# the library resolves it; you add metadata
email: auto = orm.field.eager(permission_classes=[IsAdmin])
# you narrow which rows load — named for the relation it narrows
@orm.field.eager
def posts(queryset, info) -> list[PostType]:
return queryset.filter(is_published=True)
# you write the resolver; the library cannot see inside it
@orm.field.lazy
def recent(self, info: strawberry.Info) -> list[PostType]:
return Post.objects.filter(author_id=self.id)
# ...and you say what it reads, so that loads with the parent
@orm.field.lazy(using=["comments"])
def comment_count(self, info: strawberry.Info) -> int:
return len(self.comments)A scope takes the name of the relation it narrows — posts above scopes User.posts. Unless you say otherwise with on=, a field is served by the relation sharing its name. A using= path through a scoped relation gets the same scope, so a resolver sees the rows that field would return.
By default the field name is the relation name, which means a relation can back only one field. on= lifts that: it names the relation the rows come from, so the GraphQL field can be called whatever suits your API, and one relation can have several views.
# Django
@orm.type(User)
class UserType:
published: list[PostType] = orm.field.eager(
on="posts", scope=lambda qs, info: qs.filter(is_published=True)
)
drafts: list[PostType] = orm.field.eager(
on="posts", scope=lambda qs, info: qs.filter(is_published=False)
)Both views load in one query each — three queries for the whole result set above, however many users there are — and each keeps its own scope. Without on= the second view would have to be a lazy resolver, costing a query per user.
on= is required whenever the names differ; there is no guessing from published_posts to posts, and guessing wrong on something that controls which rows a caller sees is not worth the convenience. A name that isn't a relation fails when the type is defined:
ValueError: UserType.published: on='postz' names the relation this field is
served from, but User has no relation 'postz'. Did you mean 'posts'?
Backend support. Serving two views of one relation needs somewhere to put the second, and the backends differ:
| Backend | How | Available |
|---|---|---|
| Django | Prefetch(to_attr=...) loads each view into its own attribute |
yes |
| SQLAlchemy | loader options fill the mapped attribute, so the batcher collapses per-parent statements instead | yes, for a to-many relation joined on the parent's primary key alone; not through an association table, over a to-one relation, or over a relation joined on another column or with a narrowed primaryjoin |
| Tortoise | neither a to_attr equivalent nor relation batching |
no — refused at schema-build time |
Where it cannot be eager the library says so when the type is defined rather than quietly costing you a query per row, and points you at orm.field.lazy, which is the honest spelling for that. On Django a view is read again each time rows are loaded, rather than taken from an attribute something else filled.
@decorator is sugar for name = decorator(fn), so every form has an inline spelling. Only the source of the field's type changes:
@orm.field.eager # type ← return annotation
def posts(qs, info) -> list[PostType]:
return qs.filter(is_published=True)
posts: list[PostType] = orm.field.eager( # type ← variable annotation
lambda qs, info: qs.filter(is_published=True)
)Inline is better for one-liners, and it is the only way to share a scope:
def published_only(qs, info):
return qs.filter(is_published=True)
class UserType:
posts: list[PostType] = orm.field.eager(published_only)
class TagType:
posts: list[PostType] = orm.field.eager(published_only)Both end up applying the child type's scope_rows, but they are not equivalent. Same query, same data, with PostType.scope_rows hiding drafts:
UserType.posts written as |
Queries | Drafts hidden |
|---|---|---|
posts: list[PostType] |
2 | yes |
orm.field.eager(…) with a scope |
2 | yes |
orm.field.lazy returning a queryset |
3 | yes |
orm.field.lazy returning list(...) |
5 | no |
lazy costs an extra query because the optimizer had already built the prefetch from the selection set; your resolver ignores it and runs its own. Batching keeps that at one statement rather than one per parent, but cannot remove it.
Those counts assume the batcher can rewrite your resolver's query, which it manages for a plain, filtered, ordered or excluded relation read. It cannot when the parent appears in the predicate beyond the foreign key, when the parent key sits in an OR arm, when the resolver slices per parent, when it runs its own query, or when the query holds state it cannot compare — each of those is a query per parent however the field is written. Nor can it on Tortoise, which has no rewrite at all, or with batch_relations=False. So the gap between the first two rows and the third widens to N wherever the rewrite does not hold, and a scope is the only one of them that cannot vary per parent and therefore never needs the rewrite.
The last row is the one to remember: a scope has no way to lose the scope, because it receives a query and returns a query. lazy is one list(...) away from silently returning rows the type exists to hide. Reach for lazy only when the query genuinely depends on the parent row or on info.
Because the name declares the shape, mistakes are caught when the class is defined rather than deep inside a prefetch:
@orm.field.eager
def posts(self, info) -> list[PostType]: ...
# TypeError: posts(self, ...) is not a scope: a scope receives (query, info)
# and never sees the parent row. Use orm.field.lazy for a resolver that
# needs self.It also rejects a lazy resolver without self, a scope with no type on either the annotation or the function, and scope= on a field that is not a relation on the model.
eager carries everything the optimizer needs to know about a field it resolves for you:
| Argument | Meaning |
|---|---|
scope=callable |
Narrow the rows on this relation edge; composes after scope_rows. The keyword spelling of handing eager a (query, info) callable. |
filters= / order= |
Add filter / order arguments to the field. |
compute={...} |
Computed-column hints for the optimizer store. |
disable_optimization=True |
Skip optimization for that field. |
permission_classes=[...] |
Field permissions, checked around the library's resolver, so scope= still applies. |
description= / deprecation_reason= |
Forwarded to Strawberry. |
scope= answers which rows. Its counterpart, using=, answers what to load and lives on orm.field.lazy, because that is the only place with a resolver whose reads the optimizer cannot follow. You do not need using=["posts"] when the client already selects posts { … } — the optimizer follows the selection set either way.
A declaration cannot tell you whether the batcher actually collapsed a field, because that depends on the query's shape at runtime. It reports the ones it could not, through the same lazy_resolution diagnostic that flags unoptimized loads:
Unoptimized relation loads detected (1 total, 1 unique) — may waterfall (N+1):
- path: users.written
fell back to one query per parent: the resolver ran its own query,
leaving nothing to rewrite
fix: narrow it with a scope on orm.field.eager, which cannot vary per
parent and so never needs rewriting
With lazy_resolution="warn" each finding is its own one-line warning naming only the type and field (Unoptimized relation loads detected: UserType.written fell back to one query per parent: …). The report above, with paths clipped to 160 characters and at most 8 findings, is what is logged and what "error" raises.
You get one of these when a resolver materializes its own rows, when the query cannot be rewritten to cover every parent at once, and on backends that answer asynchronously or have no rewrite at all. It is the counterpart to the guarantee eager gives you: where the name cannot promise a single query, the diagnostic tells you what really happened.
Names are validated when the type is defined, so a typo fails immediately:
ValueError: PostType.byline: Post has no relation 'athor'. Did you mean 'author'?
orm.field.eager() builds a list resolver from the model attached to the return type:
@strawberry.type
class Query:
users: list[UserType] = orm.field.eager()For a root field with custom criteria, return an unexecuted select/queryset from @orm.field.lazy — still optimized by orm.schema(). See Root custom query.
Define row scope on the type with scope_rows — see [scope_rows](#scope_rows--one-model-one-type) and the Quick Start.
Filters narrow rows within a type's query; they do not replace scope_rows — see Security and How loading works.
Generate a filter input and attach it to a type:
UserFilter = orm.filter(User)
@orm.type(User, filters=UserFilter)
class UserType:
id: auto
name: auto
email: autoList fields returning UserType then accept a filter argument:
{
users(filter: { field: { name: { exact: "Alice" } } }) {
id
name
}
}The filter covers what UserType shows — id, name and email here — and object: reaches only the relations it shows. A column the type leaves out is not filterable, because a filter on it would read it one startsWith probe at a time; to filter on a column, show it on the type. The same holds for orm.order(), orm.group() and aggregates. Through object:, a filter covers the type the relation returns: under posts(filter: {object: {author: …}}), whatever PostType.author's type shows. orm.schema() works this out for the types each schema reaches, so an admin schema can filter on a column a public schema hides even when both use the same filter; within one schema, an input serving several types covers what all of them show. A @strawberry.field resolver of your own that takes the filter does not narrow it to what it returns, because it may return anything; the filter covers the types it is attached to there too. A schema built with strawberry.Schema directly gets the inputs uncut.
Filters are recursive @oneOf trees supporting field, all, any, not, and oneOf:
# OR
{ users(filter: { any: [
{ field: { name: { exact: "Alice" } } }
{ field: { name: { exact: "Bob" } } }
] }) { name } }
# AND
{ posts(filter: { all: [
{ object: { author: { field: { id: { exact: 1 } } } } }
{ field: { isPublished: { exact: true } } }
] }) { title } }
# NOT
{ users(filter: {
not: { field: { email: { contains: "example.com" } } }
}) { name } }Built-in lookup types
StringLookup, BooleanLookup, IDLookup, IntComparisonLookup, FloatComparisonLookup, DateComparisonLookup, TimeComparisonLookup, DateTimeComparisonLookup
Typical string lookups: exact, neq, contains, iContains, startsWith, iStartsWith, endsWith, iEndsWith, inList, notInList, isNull.
Regex lookups (regex, iRegex) are disabled by default. Enable with enable_regex_filters=True. Tortoise has no regex lookup, so enable_regex_filters=True raises ValueError there.
An enabled pattern is held to 100 characters, and one that repeats a group which itself repeats a variable number of times or offers a choice ((a+)+, (\w+\s?)+, (cat|dog)+), or that refers back to a group ((a)\1), is refused. Matching such a pattern can backtrack through every way of splitting a value, and SQLite matches regexes with Python's re inside the server's process, so one request could stall every other. So is a pattern with two repeats of variable length that can match the same characters with nothing between them that the first cannot match (.*.*, a*a+, \w+\d+): each such repeat multiplies the time by the value's length. A possessive repeat or atomic group counts too (\w*\d*+), since it reads its run again each time the repeat before it gives a character back. Counted repeats that a repeat before them can also match may read at most 100 characters in all (.*x{101} is refused). A repeat of fixed length ((\d{3})+), a choice outside a repeat (^(foo|bar)$) and repeats kept apart by a character the first cannot match ([^@]+@.+) are allowed. A pattern Python's re cannot parse, reads with a warning that it may change ([[:alpha:]]), or that sets flags after its start (a(?i)b) is refused. Lookarounds in a repeat of variable count share the 100 characters, and a pattern may take at most 1,000 steps at one place in a value. What is left can still take time quadratic in a value's length for each row it is tested on, so the regex is given only values of at most max_regex_text_length characters (default 256, bytes on MySQL). A longer value does not match, and not keeps it. On SQLite each regex still costs up to about a millisecond per row it is tested on; PostgreSQL matches in the database server, outside the Python process.
When filters are registered for related models, the generated filter gains an object key for filtering by conditions on related objects:
UserFilter = orm.filter(User)
PostFilter = orm.filter(Post) # Post has an "author" relation to User{
posts(filter: {
object: { author: { field: { name: { exact: "Alice" } } } }
}) { title }
}Object traversal composes with boolean operators and supports multi-level nesting when intermediate models also have registered filters:
# Comments on posts written by Alice
{
comments(filter: {
object: { post: {
object: { author: { field: { name: { exact: "Alice" } } } }
} }
}) { body }
}The object type is @oneOf. Relations only appear in object if their target model already has a registered filter at the time orm.filter() is called -- register leaf models first. A model's filter built again once a related model has one differs from the first, so orm.schema() refuses a schema that uses both (see orm.schema()): of two models that relate to each other, the filter built first cannot traverse to the other. The same holds for orm.order() and orm.group().
Pass project={...} to control which relations appear in object and how deep traversal can go:
UserFilter = orm.filter(User)
TagFilter = orm.filter(Tag)
CommentFilter = orm.filter(Comment)
PostFilter = orm.filter(Post, project={"author": {}}) # only author, not tags/commentsSub-project dicts control nested traversal. {} means "include as a leaf" (no further object traversal). A non-empty dict lists reachable relations:
CommentFilter = orm.filter(Comment, project={
"post": {"author": {}}, # Comment -> post -> author (but not post -> tags)
})project value |
Behavior |
|---|---|
None (default) |
Auto-include all relations with registered filters |
{} |
No object type (scalar lookups only) |
{"rel": {}} |
Include rel as a leaf |
{"rel": {"nested": {}}} |
Include rel, allow traversal to nested from it |
Projected filters are cached internally and do not overwrite the global filter registry.
UserOrder = orm.order(User)Each order entry is a @oneOf input with a field key (for scalar columns), an object key (for related models) or an objects key (for the set of a to-many relation's rows). Position in the list determines tie-break priority:
{
users(order: [{ field: { name: ASC } }, { field: { email: DESC } }]) {
name
email
}
}Supported values: ASC, ASC_NULLS_FIRST, ASC_NULLS_LAST, DESC, DESC_NULLS_FIRST, DESC_NULLS_LAST.
An order list longer than max_order_entries (default 10) is refused before any SQL is built: order has 11 entries; maximum is 10.
When order types are registered for related models, the generated order gains an object key that lets you sort by fields on related objects — mirroring the filter object traversal structure:
{
posts(order: [
{ object: { author: { field: { name: ASC } } } }
{ field: { title: DESC } }
]) {
title
}
}Registration order matters: define related orders before the parent (e.g. orm.order(User) before orm.order(Post)).
objects: sorts a row by all of its related rows across a to-many relation at once. The value is the one objects: grouping keys a group by, so rows with the same set sit together, and when a connection is grouped by the set too, each group's edges are one run:
{
posts(
order: [{ objects: { tags: { field: { name: ASC } } } }, { field: { createdAt: DESC } }]
groupBy: [{ objects: { tags: { field: { name: true } } } }]
) {
edges { node { title tags { name } } }
groups { key { objects { tags { name } } } aggregates { count } edgeIndices }
}
}- The set is compared as its JSON text, such as
[["graphql"],["python"]]. On SQLite that is byte order: ascending puts a set before a shorter set it starts with ([graphql, python]before[graphql]), and the empty set[]last. On PostgreSQL it follows the database's collation. Rows with the same set always sit together, which is what grouping needs. For an order people read down, sort by a column. - Naming the relation in several entries makes one set from all their columns, in the order the entries name them, at the place of the first:
[{objects: {tags: {field: {id: ASC}}}}, {objects: {tags: {field: {name: ASC}}}}]sorts by the set of each tag'sidandname. A set sorts one way, so the entries must all be ascending or all descending. The_NULLS_FIRSTand_NULLS_LASTvalues sort as plainASCandDESC: a row with no related rows has[], nevernull. - Related rows the caller cannot see (the related type's
scope_rows, and a relation'sscope=) are left out of the set, so a post whose only tags are hidden sorts with the untagged posts. objects:offers the model's own to-many relations, not ones reached throughobject:. Order inputs take no dateinterval, so a set grouped by date periods is ordered by its full dates, and its groups' edges need not sit together.- The set is built in SQL as JSON, on PostgreSQL and SQLite; other databases raise.
orm.filter() and orm.order() auto-generate types from model introspection. When you need filter logic that goes beyond column lookups — full-text search across multiple fields, subquery-based conditions, or ordering by computed values — use orm.filter_type() and orm.order_type() with the @filter_field and @order_field decorators.
orm.filter_type(Model) is a class decorator. Annotate fields with auto for standard lookups (identical to what orm.filter() generates). Add methods decorated with @filter_field for custom logic:
# SQLAlchemy
from strawberry_orm import StrawberryORM, filter_field, auto
orm = StrawberryORM.for_sqlalchemy(dialect="postgresql", session_getter=...)
@orm.filter_type(User)
class UserFilter:
name: auto # standard StringLookup
email: auto # standard StringLookup
@filter_field
def search(self, value: str, query):
"""Full-text search across name and email."""
from sqlalchemy import or_
return query.where(
or_(User.name.ilike(f"%{value}%"), User.email.ilike(f"%{value}%"))
)
@filter_field
def has_posts(self, value: bool, query):
"""Filter users who have (or lack) any posts."""
from sqlalchemy import func, select
subq = (
select(func.count(Post.id))
.where(Post.author_id == User.id)
.correlate(User)
.scalar_subquery()
)
if value:
return query.where(subq > 0)
return query.where(subq == 0)Each @filter_field method must:
- Have a
valueparameter with a type annotation — this becomes the GraphQL input type for the field. - Have a
queryparameter — receives the backend's native query object (DjangoQuerySet, SQLAlchemySelect, or TortoiseQuerySet). - Return the modified query.
- Optionally accept an
infoparameter to receive the StrawberryInfocontext.
Where a custom filter sits decides which query it gets. At the top of the filter, alone or in a top-level all, it narrows the field's own query. Anywhere else (under not, in any or oneOf, or in a related type's filter reached through object) it gets a fresh query over its filter's model, and the rows it keeps are matched by primary key. So not: { search: "john" } returns exactly the rows search leaves out, and object: { author: { search: "john" } } tests each post's own author. Narrow the query by conditions on that model's rows, and do not rely on what it was narrowed by before.
A custom filter's value is not counted toward max_in_list_size; if it takes a list, cap it in the method.
The generated GraphQL input places custom fields as top-level keys alongside field, object, all, any, not, and oneOf:
input UserFilter @oneOf {
field: UserField # auto-generated scalar lookups
object: UserFilterObject # auto-generated relation lookups (if any)
search: String # custom
hasPosts: Boolean # custom
all: [UserFilter!]
any: [UserFilter!]
not: UserFilter
oneOf: [UserFilter!]
}Since filters are @oneOf, combine custom filters with standard lookups using all or any:
{
users(filter: { all: [
{ search: "john" },
{ field: { email: { contains: "example.com" } } }
] }) {
name
email
}
}orm.order_type(Model) works the same way. auto fields get the standard Ordering enum. Methods decorated with @order_field receive a value of type Ordering (ASC, DESC, etc.) and return the modified query:
from strawberry_orm import order_field
from strawberry_orm.types import Ordering
@orm.order_type(User)
class UserOrder:
name: auto # standard Ordering (ASC/DESC/...)
@order_field
def post_count(self, value: Ordering, query):
"""Order users by how many posts they have."""
from sqlalchemy import func
query = query.outerjoin(Post, Post.author_id == User.id).group_by(User.id)
col = func.count(Post.id)
if "DESC" in value.value:
return query.order_by(col.desc())
return query.order_by(col.asc())The generated GraphQL input:
input UserOrder @oneOf {
field: UserOrderField # auto-generated
object: UserOrderObject # auto-generated (if relations exist)
postCount: Ordering # custom
}Custom and standard orders compose naturally in the order list:
{
users(order: [
{ postCount: DESC },
{ field: { name: ASC } }
]) {
name
}
}Custom filter and order types are used exactly like auto-generated ones:
@orm.type(User, filters=UserFilter, order=UserOrder)
class UserType:
id: auto
name: auto
email: auto
@strawberry.type
class Query:
@orm.field.lazy
def users(self, info: strawberry.Info) -> list[UserType]:
return orm.get_default_queryset(User)They also work with Relay connections and orm.connection.eager().
The query manipulation inside @filter_field and @order_field methods is backend-specific since it operates on native query objects. Here are equivalent examples for each backend:
Django
from django.db.models import Q, Count, F
@orm.filter_type(User)
class UserFilter:
name: auto
@filter_field
def search(self, value: str, query):
return query.filter(Q(name__icontains=value) | Q(email__icontains=value))
@orm.order_type(User)
class UserOrder:
name: auto
@order_field
def post_count(self, value: Ordering, query):
query = query.annotate(_post_count=Count("posts"))
dir_value = value.value
if dir_value.startswith("DESC"):
return query.order_by(F("_post_count").desc())
return query.order_by(F("_post_count").asc())Tortoise
from tortoise.queryset import Q
from tortoise.functions import Count
@orm.filter_type(User)
class UserFilter:
name: auto
@filter_field
def search(self, value: str, query):
return query.filter(Q(name__icontains=value) | Q(email__icontains=value))
@orm.order_type(User)
class UserOrder:
name: auto
@order_field
def post_count(self, value: Ordering, query):
query = query.annotate(_post_count=Count("posts"))
if value.value.startswith("DESC"):
return query.order_by("-_post_count")
return query.order_by("_post_count")orm.group_type(Model) works like orm.filter_type() and orm.order_type(). auto columns get the standard group-by type (Boolean or DateGroupByOption), and an auto relation is offered under object: once its model has a group-by type of its own. Methods decorated with @group_field add custom grouping logic:
from strawberry_orm import group_field
@orm.group_type(Order)
class OrderGroupBy:
status: auto # standard Boolean group-by
created_at: auto # DateGroupByOption with interval
customer: auto # object: { customer: ... }, given orm.group(Customer)
@group_field
def by_customer_tier(self, value: bool, query):
"""Group by a computed customer tier."""
from sqlalchemy import case
return case(
(Order.amount >= 100, "premium"),
else_="standard",
).label("customer_tier")A @group_field method takes (self, value, query), plus info if it names it, and returns what to group by: a column expression on SQLAlchemy; an expression or a field name ("customer__tier") on Django; an F, a function, a Case, a field name or a pypika term on Tortoise. An (expression, label) tuple is accepted too. The group key reports the value as a string under the method's name (key { byCustomerTier }). It groups the model itself, so it cannot be reached through another model's object:.
orm.filter(), orm.order(), and orm.group() remain available for fully auto-generated types. Use orm.filter_type(), orm.order_type(), and orm.group_type() only when you need custom logic. The types produced by both APIs are interchangeable in all contexts — orm.type(Model, filters=..., order=..., group=...), orm.field.eager(filters=..., order=...), and orm.connection.eager().
Group-by and aggregation are available on Relay connection fields. Register a group-by type for a model and pass it to orm.type():
# SQLAlchemy
from strawberry import relay
from strawberry_orm import StrawberryORM, auto
from strawberry_orm.relay import ORMListConnection
orm = StrawberryORM.for_sqlalchemy(dialect="postgresql", session_getter=...)
OrderFilter = orm.filter(Order)
OrderOrder = orm.order(Order)
OrderGroupBy = orm.group(Order)
@orm.type(Order, filters=OrderFilter, order=OrderOrder, group=OrderGroupBy)
class OrderNode(relay.Node):
id: relay.NodeID[int]
status: auto
amount: auto
quantity: auto
created_at: auto
@strawberry.type
class Query:
orders: ORMListConnection[OrderNode] = orm.connection.eager()
schema = orm.schema(query=Query)When group is set, the generated connection type automatically includes aggregates, groups, and an extended pageInfo with aggregate data.
The types it adds are named after the model: OrderConnection, OrderPageInfo, OrderGroup and OrderGroupItemsConnection. A field that names a connection type of its own, class StaffOrderConnection(ORMListConnection[StaffOrderNode]), gets them named after that type instead: StaffOrderConnection, StaffOrderPageInfo, StaffOrderGroup and StaffOrderGroupItemsConnection, with a trailing Connection left off the others. Two node types over one model that both group hold different nodes, so give each its own connection type; orm.schema() refuses two that would be published under one name.
{
orders(first: 100) {
pageInfo {
hasNextPage
aggregates {
count
sum { amount }
avg { amount }
}
}
edges {
node { status amount }
}
}
}Aggregates are computed over the full filtered result set (before pagination). Page-level aggregates in pageInfo cover only the current page.
Auto-generated aggregate types include count, sum, avg, median, min, and max — scoped to the numeric and comparable fields on the model. Select a column by its GraphQL name (sum { amountTax }, min { createdAt }); anything else a client adds, such as Apollo's __typename, is ignored.
sum,avgandmediancover numeric fields and areFloat.minandmaxalso cover date, datetime and time fields, typed as the field: a date reads"2026-03-01"and a datetime an ISO 8601 instant ("2026-03-01T10:00:00+00:00"). Numeric fields areFloat.medianispercentile_cont(0.5) WITHIN GROUP (ORDER BY …), computed on PostgreSQL only; on other databases, asking for it over the result set or a group raises an error. The page-levelmedianinpageInfois worked out in memory, so it works anywhere.
{
orders(
groupBy: [{ field: { status: true } }]
first: 100
) {
groups {
key { status }
aggregates {
count
sum { amount }
avg { amount }
}
edgeIndices
items(first: 5) {
edges {
node { status amount quantity }
}
}
}
edges {
node { status amount }
}
}
}Each group includes:
key— the group-by values, as strings (nullfor rows with no value)aggregates— per-group aggregate values (count, sum, avg, min, max)edgeIndices— indices into the parent connection'sedgesarray. Anullkey matches only rows whose value is null.items— a nested cursor-paginated connection of items in that group, in the connection's order, held to the connection'smax_resultsanddefault_query_limitas its edges are
Groups come in the order of the connection's edges, so each group's edges sit together. A group is ranked by its first row under the connection's order (or the query's own ordering when there is none), then by its key. An object: order through a to-many relation does not rank groups. An objects: order does, by each group's least (or greatest) set, since a row has one set. Grouping does not need an order on the grouped column.
Grouping is bounded on three counts, each an error rather than a cut answer. A groupBy list longer than max_group_by_entries (default 10) is refused before any SQL is built. A connection whose rows make more than max_groups groups (default 100) is refused with groupBy makes more than 100 groups; filter the connection or group by fewer values; the groups are read with a LIMIT one past the cap, so no more are read. An objects: key holding more than max_group_key_rows related rows (default 100) is refused too.
A group's first row is found with MIN (or MAX for a descending clause) of each ordered column. PostgreSQL has neither for a UUID or a boolean, so a UUID is ranked by its text and a boolean as an integer (false before true); nulls fall where the connection's order puts them. A JSON, binary, hstore, full-text search vector or geometry column has no least value at all, so ordering by one does not rank groups, on any database: groups ranked only by it come in key order rather than edge order.
object: groups by a column of a related row, through a foreign key, a reverse foreign key or a many-to-many relation. The key nests one level per relation, and you can group by any column the related type shows, not only its primary key:
{
posts(
groupBy: [{ object: { author: { field: { id: true } } } },
{ object: { author: { field: { name: true } } } }]
order: [{ object: { author: { field: { name: ASC } } } }]
) {
groups {
key { author { id name } }
aggregates { count sum { views } }
edgeIndices
}
}
}- A relation is offered when the related model has a group-by type (
orm.group(Author), registered first) and the type shows the relation as stored, e.g.author: AuthorNode | None. - Grouping reads the related row through the related type's
scope_rows. A row with no related row, or one the caller cannot see, is grouped under a key whose related values are allnull—{ author: { id: null, name: null } }, not{ author: null }— as the field reads on the type. - Across a to-many relation (
tags, or a reverse foreign key such asauthor.posts), a row is grouped once under each distinct key its visible related rows give, and once undernullif it has none. A post taggedpythonandrustis counted in both groups, and in its own edge'sedgeIndicesfor each. The groups' counts can therefore add up to more thantotalCount. To put each row in one group, keyed by the set of its related rows, useobjects:. - A to-many relation can only be the first relation in a path.
A relation the type shows through its own resolver (@strawberry.field def category(self) -> CategoryNode) is not offered, because the ORM cannot tell what the resolver returns. You can show the relation as stored (category: CategoryNode | None), show its foreign key column (category_id: auto) and group by that, or declare a @group_field that returns the column you want to group by.
objects: groups a row by all of its related rows across a to-many relation at once, so each row is in exactly one group. A post tagged graphql and python falls in the [graphql, python] group, together with every other post tagged exactly those two. It is not counted under graphql and again under python, and the groups' counts add up to totalCount:
{
posts(groupBy: [{ objects: { tags: { field: { name: true } } } }]) {
groups {
key { objects { tags { name } } } # [{name: "graphql"}, {name: "python"}]
aggregates { count }
edgeIndices
items(first: 5) { edges { node { title } } }
}
}
}objects:offers the to-many relationsobject:offers (many-to-many and reverse foreign keys) on the model itself. Under each one,field:names the related rows' columns the set is made of. Naming the relation in several entries adds their columns to the same set:[{objects: {tags: {field: {id: true}}}}, {objects: {tags: {field: {name: true}}}}]keys each group bytags { id name }.- The key's
objects { tags }is a list of the related keys, distinct and sorted by their values. Two posts are in the same group when their related rows give the same values. A post with no tags, or only tags the caller cannot see, is in the[]group. Hidden rows are left out of the set, as the field reads on the type. - A date column takes an
interval, as it does underfield:. Each related row's date is cut to its period before the set is made, so two January posts make one2026-01-01entry. - The set is built in SQL as JSON, on PostgreSQL and SQLite; other databases raise, as date intervals do.
objects:can be combined withfield:,object:and@group_fieldentries in the samegroupBy.- A key holding more than
max_group_key_rowsrelated rows (default 100) is refused:objects: puts more than 100 related rows in one group key. The database builds the key before it is counted, so the cap bounds the answer, not the work. - To keep each group's edges together, order by the same set:
order: [{objects: {tags: {field: {name: ASC}}}}]. Each row then sorts by its group's key, and a group'sitemscome in that order.
Date/datetime fields support interval-based grouping:
{
orders(
groupBy: [{ field: { createdAt: { interval: MONTH } } }]
) {
groups {
key { createdAt }
aggregates { count }
}
}
}Supported intervals: DAY, WEEK (starting Monday), MONTH, QUARTER, YEAR. The key is the start of the period in ISO 8601: "2026-03-01T00:00:00" for a datetime field, "2026-03-01" for a date field. On Django the period is cut in the current time zone when USE_TZ is on, and the key carries its offset ("2026-03-01T00:00:00-05:00"). SQLAlchemy and Tortoise cut periods on PostgreSQL (in the session's time zone) and SQLite; other databases raise an error.
Use @aggregate_field to define computed aggregate expressions:
from strawberry_orm import aggregate_field
@orm.aggregate_type(Order)
class OrderAggregation:
amount: auto
quantity: auto
@aggregate_field
def total_revenue(self, columns) -> float:
from sqlalchemy import func
return func.sum(columns.amount * columns.quantity)A GraphQL error aborts the field and hands the client an errors array detached from the shape it asked for. If you would rather answer with a typed payload — data when the work succeeded, errors when it did not — orm.payload builds it.
Configure it once with the error type and how to convert an exception:
# Django
from strawberry_orm import PayloadPolicy, StrawberryORM
orm = StrawberryORM.for_django(
payload=PayloadPolicy(
errors=ErrorsObject,
on_error=ErrorsObject.from_exception,
),
)Then the resolver says what it returns, and the payload type is generated from it:
# Django
@strawberry.type
class Query:
@orm.payload.query
def recent_users(self) -> list[UserType]:
return User.objects.order_by("-created_at")
@strawberry.type
class Mutation:
@orm.payload.mutation
def rename_user(self, identifier: str, name: str) -> UserType:
...recentUsers returns a RecentUsersPayload with data and errors. The name comes from the resolver; pass name= to choose your own. orm.payload.mutation also takes input_mutation=True to collapse the arguments into a generated input argument.
Three things happen for you. Exceptions become errors and leave data null. Sync ORM work is moved off the event loop under async, decided per call so the same resolver is correct in tests and under an ASGI server. And rows returned through data are eager-loaded, because data is a resolved field like any other — the payload machinery itself does no optimization.
on_error is the whole translation step. It receives the exception and returns a value of your errors type:
# Django
@strawberry.type
class ErrorsObject:
message: str
field: str | None = None
@classmethod
def from_exception(cls, exc: BaseException) -> "ErrorsObject":
if isinstance(exc, ValidationError):
return cls(message=str(exc), field=exc.field)
if isinstance(exc, AuthorizationError):
return cls(message="Not allowed")
raise exc # anything unrecognised stays a GraphQL errorGiven raise ValidationError("Title is required", field="title"), a client asking for
{ createPost(title: "") { data { id title } errors { message field } } }gets its answer in the shape it asked for, with data null:
{ "data": { "createPost": { "data": null,
"errors": { "message": "Title is required",
"field": "title" } } } }Exactly one of data and errors is ever set.
That final raise matters: a converter that only recognises some of your errors needs a way to let the rest through. Anything on_error re-raises fails the field normally, so createPost comes back null with a top-level GraphQL error — a bug stays a bug rather than being flattened into a message.
handles is the other way to draw that line. It decides what is caught in the first place, so an unlisted exception never reaches the converter and keeps its own traceback instead of being chained through one:
# Django
PayloadPolicy(
errors=ErrorsObject,
on_error=ErrorsObject.from_exception,
handles=(ValidationError, AuthorizationError),
)The default is (Exception,), which catches broadly and leaves the decision to on_error. Which you prefer is a question of where the list of known errors should live: next to the policy, or inside the converter.
A schema that keeps its types in one module and its resolvers in several hits a wall: -> list["UserType"] is resolved against the module that wrote it, which may never have imported the name. types says where to look instead:
# Django
PayloadPolicy(
errors=ErrorsObject,
on_error=ErrorsObject.from_exception,
types="app.api.graphql.objects",
)Names in a payload's return annotation are then resolved there before the payload type is built, so a resolver can name any type in that module without importing it.
The errors type can be named the same way, which is usually necessary: the module defining it generally imports the ORM, so importing it back would be a cycle.
orm.payload.connection puts a Relay connection under data, with the generated filter / order / groupBy arguments and pagination hanging off it. Name the node type in the return annotation and the connection follows from it:
# Django
@strawberry.type
class Query:
@orm.payload.connection()
def users(self) -> list[UserNode]:
return User.objects.order_by("id")Pass ORMListConnection[UserNode] explicitly instead when you want a connection type of your own.
{
users {
errors { message }
data(first: 10, filter: { field: { name: { contains: "a" } } }) {
totalCount
edges { node { name } }
}
}
}On failure data is an empty connection rather than null, so a client renders the same shape either way.
Write plain @strawberry.mutation resolvers and use strawberry-orm for generated input types. Authorization and row-level checks are your responsibility — see Security.
CreatePostInput = orm.input(Post, include=["title", "body", "author_id"])
@strawberry.type
class Mutation:
@strawberry.mutation
def create_post(self, info: strawberry.types.Info, input: CreatePostInput) -> PostType:
post = Post(title=input.title, body=input.body, author_id=input.author_id)
...
return postorm.ref(...) generates a @oneOf input for managing related lists:
CreateTagInput = orm.input(Tag, include=["name"])
@strawberry.input
class UpdateTagInput:
id: strawberry.ID
name: str | None = strawberry.UNSET
TagRef = orm.ref(Tag, create=CreateTagInput, update=UpdateTagInput, unlink=True, delete=True)Each ref is a @oneOf with these keys:
update— link an existing object by ID, or update its fields. Always present (an ID-only input is auto-generated if no customupdatetype is provided).create— create a new related object (present whencreate=is provided).unlink— remove the object from the relation without deleting it (present whenunlink=True).delete— hard-delete the related row (present whendelete=True).
All list mutations use patch semantics: only the items you mention are affected; existing related objects not listed are left untouched.
Apply ref operations with orm.apply_ref_list(parent, "relation_name", refs, info). The list is one unit of work, the same as an upsert's, so a refusal part-way through leaves nothing written. unlink and delete act only on rows currently in parent's relation; any other id raises UpsertNotFoundError, and unlinking from a relation whose foreign key is not nullable is a validation error. A delete goes through the repo's _delete, so a soft-delete override is honoured, on an async session and on Tortoise as well: _delete_async calls an override of _delete (as _create_async, _get_async and _save_async call theirs).
An optional authorize callback (action, model, obj_id, info) -> bool adds a per-item check on top of the model's repo. For a row of a subclass it is asked once for each model the row belongs to, base first. obj_id is the row's primary key as the model stores it (1, never "01" or a Relay global ID), or None for a create. It is asked once the row is read, so obj_id is the key the row holds even where the database matched the caller's spelling regardless of case ("secret" for {delete: {id: "SECRET"}} on a NOCASE column), and it is never asked about a row the repo's scope_query hides or that does not exist: an update of one is skipped, and an unlink or delete of a row not in the relation raises UpsertNotFoundError whatever authorize would say. An item it denies is skipped, and an item it allows must still pass the repo's scope_query and can_* hooks. An update that takes a row from another parent asks that parent's can_unlink as well as this one's can_link. A row whose key is its foreign key to the parent cannot be moved to another parent, which would give it the key of the row already there; this raises UpsertValidationError. authorize is not told which parent an item joins or leaves; can_link(parent, field, instance, info) and can_unlink are, and a row a create makes is asked can_link too, once it exists, since through a many-to-many list can_create's data does not name the parent.
mutation {
setPostTags(postId: 1, tags: [
{ update: { id: "2" } }
{ update: { id: "1", name: "python3" } }
{ create: { name: "new-tag" } }
{ unlink: { id: "3" } }
{ delete: { id: "4" } }
]) {
tags { id name }
}
}Note: Whether the order of items in the list affects the final ordering of the relation is an implementation detail that each backend must maintain.
orm.mutations.create_node_input() and orm.mutations.update_node_input() generate a catch-all @oneOf input carrying one branch per registered Relay Node type, with recursive nested ref lists. The library deliberately does not ship a resolver that executes them — you write the mutation, so the write path (and its scoping) stays yours. The exception is an upsert input, which orm.apply_upsert() can execute for you; see Applying an upsert.
@orm.type(Post)
class PostNode(relay.Node):
id: relay.NodeID[int]
title: auto
body: auto
CreateNodeInput = orm.mutations.create_node_input(name="CreateNodeInput")
@strawberry.type
class Mutation:
@strawberry.mutation
def create_node(self, info: strawberry.Info, input: CreateNodeInput) -> bool:
# Exactly one root branch is set. Authorize it, then write it yourself.
...scope_rows is a read control and does not scope writes — see Security. Because the resolver is yours, apply the same restriction there, or use a repo (AbstractRepo) whose can_* checks, scope_query, and on_* lifecycle hooks run for every write the library performs through orm.apply_ref_list().
project= is a path-shaped dict that controls which relations appear in the generated input, and how each behaves:
project = {
"post": {
"author": {"_meta": {"onReplace": ["DISCONNECT", "DELETE"]}},
"comments": {"author": {}},
"tags": {},
},
}
CreateNodeInput = orm.mutations.create_node_input(
project=project, name="CreateNodeInput"
)Rules:
- Root keys are model names (
post,comment, ...). - Nested keys are relation names on that model.
_metaconfigures behavior for that relation subtree (create,update,upsert,unlink,delete,onReplace,immutable,maxVisits,name).- A
_metanaming none ofcreate,update,upsert,unlinkanddeleteofferscreateandupdate(createalone withimmutable). One naming any of them offers only those, through every input built from it: anupsertarm offerscreateonly with_meta.createandupdateonly with_meta.update, each limited to the fields that key lists, andcreate_node_input()andupdate_node_input()refuse a model whose projection does not offer their operation. So{"update": ["title"], "upsert": {"where": ["id"]}}can match a row and change its title, but never create one. - Relations you do not declare are absent from the input, so the schema rejects them.
- Destructive operations are opt-in. A to-many relation offers
createandupdateunless its_metasetsunlink: Trueordelete: True, and a re-pointed single link disconnects the row it replaces unlessonReplaceoffers"DELETE". Even then the replaced row is deleted only if the caller could delete it by its key: one the related repo'sscope_queryhides, or whose deletionauthorizedenies, is disconnected and left in place. If deleting it would also delete rows the caller could not delete, the write is refused withPermissionError. - A SQLAlchemy relationship with a
delete-orphancascade, a many-to-many one included, deletes every row it lets go of, so letting go of one is a delete. Unlinking from one is refused (senddelete, which goes through the repo), and re-pointing a single link of that kind is refused unless the caller could delete the row it held:authorize, the related repo'sscope_queryandcan_deletedecide, andon_before_deleteruns, before the cascade deletes it. The rows its deletion cascades to are held to the same checks. - A delete the library performs is refused with
PermissionErrorunless every row it takes with it could be deleted too: the rows that Django'son_delete=CASCADEorDB_CASCADE, a SQLAlchemycascade="delete"relationship or anondelete="CASCADE"foreign key on a table mapped in the same registry, or Tortoise'son_delete=CASCADEdeletes along with it. Each such row a repo orauthorize=governs must be one its own repo'sscope_queryshows, whosecan_deleteallows it, and thatauthorizedoes not deny. Theiron_before_deleteand_deleteare not called. A cascade the models do not declare, such as a migration'sON DELETE CASCADEor a foreign key in a table no mapper maps, is not seen: declare it on the model, or refuse the parent's delete incan_delete. A foreign key that is set to null or its default instead (SET_NULL,SET_DEFAULT,DB_SET_NULL,ON DELETE SET NULL, or SQLAlchemy nulling the children of a relationship with no delete cascade) is cleared without asking the referencing row's repo: the row it named is gone, and asking would let any row that points at yours stop you deleting it. DeclarePROTECTorRESTRICTwhere a reference should stop the delete. - Columns that the model's
@orm.type(..., exclude=[...])hides are left out of every generated input, and so are those a type over one of its base models hides, since a subclass row (an inherited SQLAlchemy mapping, a Django proxy or multi-table child) is a row of its base too. Naming one in_meta.create,_meta.updateor_meta.upsert.whereraisesValueError, and so does declaring the type after an input that already writes the column or whose upsertwherematches on it. - Foreign key columns are written through their relation, so they are left out, and so are both columns of a Django
GenericForeignKey, itsobject_idand the foreign key toContentTypesaying which model that key is for: no relation reaches the row they name to ask that row's repo, so neither can be matched on inwhere, and a projection naming either, or the content type's relation, raisesValueError. - So are the relations it hides, and a link whose foreign key column it hides:
exclude=["author_id"]leaves outauthor. Naming such a relation inproject=raisesValueError, and so does declaring the type after an input that already writes it. - Columns that name a row are left out: primary keys, inherited keys and parent links, and a link that is the row's own key. Naming one in
_meta.create,_meta.updateor_meta.upsert.where(other thanwhere: ["id"]) raisesValueError. - Relations with sensitive-looking names (
roles,groups,permissions) are left out unlessproject=names them, as sensitive-looking columns are unless_metalists them.
_meta.upsert.where adds an upsert arm made of where, and of create and update where the projection names them. A list of field names makes those fields required, and a row matches only when all of them do. where: True exposes every writable scalar plus id as optional fields, so the caller chooses which fields to match on and the match uses the ones that were sent. Each is a column a caller can test the value of, whether or not the type shows it (write inputs follow the model):
project = {
"_meta": {"create": True, "update": True, "upsert": {"where": ["email"]}},
"posts": {
"_meta": {"create": True, "upsert": {"where": True}},
},
}
UpsertUserInput = orm.mutations.upsert_node_input(
model=User, project=project, name="UpsertUserInput"
)Here a user is created or updated, and a post is created or matched but never changed: its projection names no update. upsert_node_input() builds the same upsert input as a standalone root for one model; project is that model's subtree and must declare _meta.upsert.where. Every generated input class carries the model it writes as __orm_model__, so a resolver can walk a nested input without looking the relations up again. Fields left unset in an optional where are strawberry.UNSET.
By default a matched row is updated from update where the projection names update, and left alone where it does not. _meta.upsert.onMatch chooses otherwise, per projection:
onMatch |
A matched row is… | Nested rows under it | Generated upsert input |
|---|---|---|---|
"UPDATE" (default with _meta.update) |
updated from update |
applied from update |
{where!, create, update} |
"IGNORE" (default without it) |
left alone | not applied | {where!, create} |
"APPEND" |
left alone | applied from create, with the matched row as parent |
{where!, create} |
create is in the generated input only where the projection names _meta.create. Setting onMatch: "UPDATE" explicitly requires _meta.update, so the fields a match may change are stated rather than implied. Under "APPEND", each nested to-many item still follows its own projection: an item that is itself an upsert is matched under the parent and applies its own onMatch.
_meta.immutable: True is shorthand for a row that is written once and never changed. It removes update, unlink, delete and onReplace from the projection, and matches with "APPEND" unless you set onMatch: "IGNORE". Combining it with any of those keys is an error naming the model and keys, as is onMatch without where. A projection whose update is disabled generates no *Patch or *Update types, and a link to an immutable target has no onReplace, because the link can never be re-pointed.
The policy belongs to the projection, so a named projection reused recursively (_meta.name) applies the same rules everywhere it appears, and one tree can mix immutable and mutable projections. When any of these keys is set, the generated where, create and upsert fields carry a description of what a match does ("Matched rows are not modified; nested rows are appended.").
A single link is written only when its row is created. Sending one for a row that turns out to match is a validation error, because it would silently do nothing; set _meta.upsert.onMatchLinks: "IGNORE" (with onMatch: "APPEND") to skip it instead. To link an existing row without ever creating one, give its projection {"upsert": {"where": ["id"]}} and neither create nor update, or send upsert: {where: {id}} and no create: a match links it without writing to it, and a miss raises UpsertNotFoundError. where.id accepts a raw primary key or a Relay global ID.
_meta.maxVisits: N caps how many times the model may appear on one nesting path, which bounds how deep a recursive projection can be sent. It is checked before anything is written.
An insert-only people schema, where re-sending a person who already exists only adds their new events:
def immutable(name, where, **meta):
return {"_meta": {"name": name, "immutable": True, "create": True,
"upsert": {"where": where}, **meta}}
person = immutable("Person", ["ssn", "dob"])
person["events"] = immutable("Event", ["kind", "occurred_on"])
address = immutable("Address", ["line1"])
address["person"] = immutable("PersonRef", ["ssn", "dob"])
PersonInput = orm.mutations.upsert_node_input(model=Person, project=person, name="PersonInput")
AddressInput = orm.mutations.upsert_node_input(model=Address, project=address, name="AddressInput")input PersonInput { where: PersonWhere! create: PersonCreate }
input PersonEventsItem @oneOf { create: EventCreate upsert: EventUpsert }
input EventUpsert { where: EventWhere! create: EventCreate }
input AddressPersonLink @oneOf { create: PersonRefCreate upsert: PersonRefUpsert }orm.apply_upsert(input, info, *, authorize=None) executes an input built by upsert_node_input() and returns the matched or created row. The upsert arm of orm.apply_ref_list() runs through the same code. All three backends implement both. Await the result on an async SQLAlchemy session, in an async Django resolver, and always on Tortoise.
@strawberry.mutation
def save_person(self, info: strawberry.Info, input: PersonInput) -> PersonNode:
return orm.apply_upsert(input, info) # await it where the backend is asyncFor each upsert in the payload:
- The lookup uses the sent
wherefields, scoped to the parent row for a nested item, and runs through the repo'sscope_query. - On a miss with
create, the row is created fromcreatemerged withwhere(exceptid), through the normal create path (on_before_create,can_create,on_after_create). Because of that merge, awherefield thatcreatedoes not offer cannot be sent together withcreate; validation rejects it. - On a miss without
create,UpsertNotFoundErroris raised. - On a match,
onMatchapplies. A matched person with two new events issues noUPDATE, only twoINSERTs.
The whole payload is validated before the first write: operations the projection does not allow, an empty where, a nested item that sets the foreign key back to its parent, and maxVisits. This holds for payloads built in Python too. The write is one unit, so an error at any depth leaves nothing behind:
| Backend | Unit of work |
|---|---|
| SQLAlchemy | A savepoint of your session. It does not commit; that stays with your session handling. |
| Django | transaction.atomic() on the model's write database, run through sync_to_async in an async context. |
| Tortoise | in_transaction() on the connection the model's rows are written to: the router's db_for_write, else the model's own. |
Django's atomic() and Tortoise's in_transaction() commit when they are the outermost transaction, and become a savepoint inside one you opened, such as ATOMIC_REQUESTS.
A write decides on what it reads: the rows it looks up, its repos' scope_query, and the queries its hooks and authorize make. Read from a replica that lags, those would be rows as they were: a row since given to someone else would still pass the scope, and a revoked grant would still let can_update through. So while orm.apply_upsert() or orm.apply_ref_list() runs, strawberry_orm.is_writing() is true and every read the write makes goes where the write goes.
| Backend | How a write's reads follow it |
|---|---|
| Django | On each write, a router of the library's own goes first among DATABASE_ROUTERS. While a write runs it answers db_for_read with your routers' db_for_write; otherwise it does not answer. A query that names its database (.using("replica")) still reads there. |
| Tortoise | The same, among the routers given to Tortoise.init(). A query given using_db= still reads there. |
| SQLAlchemy | Your session routes its own reads, in get_bind(). It must send them where writes go while is_writing() is true. |
from sqlalchemy import Delete, Insert, Update
from sqlalchemy.orm import Session
from strawberry_orm import is_writing
class RoutingSession(Session):
def get_bind(self, mapper=None, *, clause=None, bind=None, **kw):
if bind is not None:
return bind
if self._flushing or is_writing() or isinstance(clause, (Insert, Update, Delete)):
return engines["primary"]
return engines["replica"]On SQLAlchemy, a write is refused with TypeError before it reads anything if, for any model of the written model's registry that the session binds, get_bind() picks one database for a select and another for an update.
Two repo hooks are specific to upserts:
| Hook | Called |
|---|---|
find_for_upsert(model, query, info) |
to find the match; query maps the sent where fields (plus the parent's foreign key when nested) to values. Override for a custom lookup; on async, an async def override, or find_for_upsert_async, is awaited. The default returns an awaitable on an async SQLAlchemy session and on Tortoise, so await it when calling super(). The row an override returns is read again through scope_query, and one it hides counts as no match. |
can_upsert(instance, info) / on_match(instance, info) |
once per matched row, after authorization. on_match may be async on an async SQLAlchemy session and on Tortoise; Django runs the write synchronously, so its hooks must be sync. |
authorize(action, model, pk, info) sees "upsert" for a match and "create" for a miss, alongside "update", "unlink" and "delete" for nested items. Unlike a plain apply_ref_list item, which is skipped when authorize returns False, every denial inside an upsert raises PermissionError, so a write is never partly applied. A keyed row is read before authorize is asked about it, with the key the row stores, so a row the repos hide or that does not exist raises UpsertNotFoundError, never PermissionError. authorize runs in addition to the repo's hooks, never instead of them.
Re-pointing a single link asks the target model's repo can_link for the row it now points at, whether it existed or the write creates it, and can_unlink for the row it replaced. A row created into a to-many list is asked can_link as well. On SQLAlchemy, a one-to-one written from the row without the foreign key (User.profile, with Profile.user_id) takes its new target from the row that held it, so that row's can_unlink is asked too. So does one written from the side with the key: pointing a new or existing profile's user at a user who has a profile takes the user from that profile, which must be one the repo's scope_query shows and whose can_unlink allows it, and where User.profile deletes orphans, the profile left behind is held to the delete checks before the cascade deletes it.
Validation failures raise UpsertValidationError (a ValueError); a missing row raises UpsertNotFoundError (a LookupError).
strawberry-orm works with Strawberry's Relay support for cursor-based pagination and global node identification.
Extend relay.Node instead of a plain Strawberry type. Use relay.NodeID for the id field:
# SQLAlchemy
from strawberry import relay
from strawberry_orm import StrawberryORM, auto
orm = StrawberryORM.for_sqlalchemy(dialect="postgresql", session_getter=...)
UserFilter = orm.filter(User)
UserOrder = orm.order(User)
@orm.type(User, filters=UserFilter, order=UserOrder)
class UserNode(relay.Node):
id: relay.NodeID[int]
name: auto
email: autoA field typed as an interface, relay.Node say, or a union can return model rows as they are: each row takes the type over its model, or over its nearest class for a model subclass. When the schema has two types over the row's model, a PublicUser and a StaffUser over User, the row is refused rather than given either, since one can show columns the other excludes. Return strawberry.cast(PublicUser, row) to choose, or give the types an is_type_of of their own. node(id:) and nodes(ids:) already give each row the type its ID names.
The optimizer plans each row as the type it is read as: a row cast with strawberry.cast loads what its type's using= paths and scope= say, and rows whose type an is_type_of of your own decides load each relation with only the rows every type they may be read as allows. A cast holds only in the execution that makes it. Rows that outlive a request are not read as the type an earlier request cast them to, whether your resolver, a list field of the library's or node() made that cast, and a cast made before schema.execute() is not seen inside it. Cast in the resolver.
Use orm.connection.eager() with ORMListConnection to create paginated connection fields. Filters and ordering from the node type are automatically wired in:
from collections.abc import Iterable
from strawberry_orm.relay import ORMListConnection
@strawberry.type
class Query:
@orm.connection(ORMListConnection[UserNode])
def users_connection(self) -> Iterable[UserNode]:
return orm.get_default_queryset(User)This gives you:
{
usersConnection(
filter: { field: { email: { contains: "example.com" } } }
order: [{ field: { name: DESC } }]
first: 10
after: "YXJyYXljb25uZWN0aW9uOjk="
) {
edges {
cursor
node { name email }
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
}Filters and ordering are applied before pagination, so the connection always slices from a correctly filtered and sorted result set.
orm.connection raises a TypeError for a keyword it does not accept, listing the ones it does, so a misspelling fails where you write it.
Whichever connection type you name — ORMListConnection, ORMConnection, or Strawberry's ListConnection or Connection, with the node class or its name as a string — the page is cut as described below. A connection type of your own must derive from ORMListConnection; the schema refuses to build with one that would slice its rows in Python.
A field declared with Strawberry's own relay.connection is paged the same way. Its rows are held to scope_rows before anything counts or slices them, so no edge, cursor, pageInfo flag or totalCount counts a row the scope hides, and no hidden row shows up as a null node in its place. That holds over an interface or a union an @orm.type belongs to as well; a connection over a union keeps its type, and Strawberry pages its rows once they are held to scope. A field that would page rows of a model any other way is refused when the schema is built: a resolver that builds its own connection, a type with a connection as an attribute, or paging by a ConnectionExtension other than Strawberry's. Declare it with orm.connection or relay.connection and return the rows. A schema built with strawberry.Schema directly cannot be changed as it builds, so its fields keep Strawberry's paging; under orm.optimizer_extension(), a connection paged that way is refused as it resolves (Cannot page posts: its pages would count rows the caller cannot read.), unless it is an ORMListConnection or an orm.connection. Without that extension, a relay.connection over rows is refused the same way, and an orm.connection holds its counts to scope itself, though the rows it would serve are refused (see orm.schema()).
The page is cut in the database, not in Python. first: 50 reads 51 rows (the extra one answers hasNextPage), after becomes an OFFSET, and totalCount is a separate count sent only when it is selected — and not even then when the page comes back short, because a short page is the end of the result. last without before counts first, to find where the window starts. Cursors are the same either way. Each page is its own query, and a database may break ties in a non-unique order differently from one query to the next, so a row could land on two pages and another on none. The cut therefore ends every order — the client's, the resolver's or the model's — with the primary key, unless it already includes it; with no order at all, the primary key alone orders the pages. Rows that do not tie keep their order. A Django queryset the resolver already sliced, or ordered with .extra(order_by=...), is cut in the order it has.
On SQLAlchemy, a join to a collection repeats a row once per related row, and .unique() folds the repeats together after reading, keeping each row where it first appears. The page is cut the same way in SQL: each row is numbered by its first appearance, so first: 1 reads one row however many related rows it has, and ordering through a to-many relation pages in the database too.
A few requests are still read whole and sliced in Python: a resolver that returns rows rather than a query and, on SQLAlchemy, a join that can repeat a row (one without .distinct()) when it also selects more than one entity, has a second FROM, or was already cut with a LIMIT or OFFSET, which count joined rows. Under loader options other than with_loader_criteria, such as contains_eager, the page is still cut by the database, and each entity on it is read with every row its join makes of it.
Every page is held to one page's worth of rows. first and last are capped at max_results (100 by default, set per field or with Strawberry's relay_max_results) and at default_query_limit when that is smaller, which is also the page size when neither is given. Three requests are answered differently from Strawberry's ListConnection, which slices a Python list:
beforewithoutfirstorlastreads one page from the start, not every row up to the cursor.last: 0returns no edges, at the end of the result:hasPreviousPageis true when rows follow the cursor (or, with none, when there are any rows),hasNextPagefalse.- A cursor before the first row is refused (
Argument 'after' cannot point before the first item.). Strawberry counted it from the end of the list.
default_query_limit caps each page, not the rows paged through, so totalCount counts every row and every page is reachable. A connection resolver returning orm.get_default_queryset(Model) is the exception: that query is already cut to the limit.
orm.connection.eager() accepts the same keyword arguments as relay.connection() — name, description, deprecation_reason, extensions, and max_results.
The decorator above is one way to give orm.connection.eager() a resolver. You can also pass one by keyword, which is what you want when the connection is a field on a type you are assembling rather than a method you are writing:
# Django
def recent_users(info: strawberry.types.Info) -> Iterable[UserNode]:
return User.objects.order_by("-created_at")
@strawberry.type
class Query:
users = orm.connection(ORMListConnection[UserNode], resolver=recent_users)Either way the library still builds everything around your rows: the generated filter, order, and groupBy arguments, the grouped connection type when the node declares a group-by, totalCount, and optimizer integration. Your resolver does not need to accept filter or order — they are applied to the query object you return. Arguments of your own are passed through and appear on the field.
orm.mutations.create_node_input() and orm.mutations.update_node_input() generate catch-all Relay Node mutation inputs with recursive nested refs; you supply the resolver. See Node Mutation Inputs for full documentation.
strawberry-orm supports both sync and async execution (schema.execute / schema.execute_sync, Django AsyncGraphQLView, etc.).
| Backend | Pattern |
|---|---|
| Django | django_async_safe=True (default) wraps generated and @orm.type resolvers with sync_to_async when the event loop is running. Use orm.schema() for eager loads (enabled by default). |
| SQLAlchemy | Pass a sync Session or AsyncSession via session_getter. Both work transparently. |
| Tortoise | Async-first. Use async def resolvers and await ORM calls. |
orm = StrawberryORM.for_django() # django_async_safe=True, lazy_resolution="warn"
schema = orm.schema(query=Query)Custom sync resolvers declared with @orm.field.lazy are async-safe automatically. Automatic filter and order arguments are wired on generated list and connection fields; pass them explicitly via @orm.field.lazy(filters=..., order=...) if a hand-written resolver needs them.
Sync @orm.connection resolvers on @orm.type work under async execution, including when the method name matches a Django reverse relation (e.g. def comments(self, info: strawberry.Info) returning a queryset).
Optional runtime FK checks: extensions=[orm.lazy_resolution_extension()].
# Tortoise example
@strawberry.type
class Query:
@strawberry.field
async def users(self) -> list[UserType]:
return await User.all()apply_ref_list is sync for Django/sync-SQLAlchemy and awaitable for Tortoise/async-SQLAlchemy.
With a sync SQLAlchemy Session under async execution (subscriptions, schema.execute), the library's own reads run on the event loop by default. That includes counts, a statement a resolver returned, eager loads, and loading the relations of rows a resolver handed back. If your session refuses use from the loop's thread, pass offload_sync_session=True: those reads then go through sync_to_async(thread_sensitive=True), one thread per operation, as Django's do. Leave it off for in-memory SQLite, whose connection pool gives each thread a database of its own. Writes (upserts, orm.ref lists, repo creates) are not moved.
Give each request its own session: SQLAlchemy does not support one Session or AsyncSession in use by concurrent tasks. Shared anyway, the requests share its rows, and a relation one request's scope loaded sits on the row the other reads. The library trusts a relation only as the statement that loaded it marked it, together with the rows that statement loaded, and only while the relation still holds those rows; otherwise the relation is read again under the reading request's scope, at the cost of a query.
If your resolvers return a query object of your own that wraps the ORM's, pass to_query= to map it once, rather than in every resolver:
orm = StrawberryORM.for_sqlalchemy(
dialect="postgresql",
session_getter=...,
to_query=lambda result, info: result.select if isinstance(result, MyQuery) else result,
)It is called on every result an orm.field, orm.connection, orm.payload.query or orm.payload.connection resolver hands the library, before the library decides between a query and rows, including orm.field.lazy(filters=…, order=…) and @orm.field.eager() resolvers, whose client filter and order then apply to the converted query. A connection over the converted result then filters, orders and pages in the database. info is None when the resolver does not take it.
Optional plugins live in strawberry_orm.contrib. Each has its own extra, so its dependencies are only installed when you ask for them.
strawberry_orm.contrib.mcp serves a schema as an MCP server whose tools are GraphQL operations you write. Each named operation in a document becomes one tool, so an AI client calls ListPosts(first: 5) instead of writing GraphQL, and can only do what your operations do. There is no model on the server.
pip install "strawberry-orm[contrib.mcp]"from strawberry_orm.contrib.mcp import mcp_server
OPERATIONS = '''
"""Published posts, newest first."""
query ListPosts(
"""How many to return, at most 50."""
$first: Int = 10
$filter: PostFilter
) {
posts(first: $first, filter: $filter) { ...PostSummary }
}
"""Publish a draft post. The author must be the caller."""
mutation PublishPost($id: ID!) {
publishPost(id: $id) { ...PostSummary }
}
fragment PostSummary on Post { id title author { name } }
'''
async def get_context(request):
user = await user_for_token(request.headers.get("authorization"))
return {"request": request, "user": user}
server = mcp_server(schema, operations=OPERATIONS, context_getter=get_context)
app = server.streamable_http_app()
# uvicorn app:app, then point an MCP client at http://localhost:8000/mcpA call returns the GraphQL result:
{"data": {"posts": [{"id": "1", "title": "Hello", "author": {"name": "Alice"}}]}}-
The document is the tool definition. An operation's name is the tool's name and its description is the tool's description; without one the tool says which operation it runs. Its variables, with their descriptions and defaults, are the tool's arguments, published as a JSON Schema that includes your input types and enums. Its selection set is the tool's output schema, so clients know the shape of
data. Fragments may be shared between operations. Subscriptions and anonymous operations are refused. -
Checked at startup. The document is validated against the schema when the server is built, so a schema change that breaks a tool fails then, not on a call.
-
Queries read, mutations are marked. Query tools carry MCP's
readOnlyHintand mutation toolsdestructiveHint, which clients use to ask their user before a change. Nothing else can run: a client can only call the operations you listed. -
Your permissions apply. Every operation runs through the schema with the context from
context_getter, soscope_rows,scope=, permission classes and the optimizer behave as for any other request. Over stdio,context_getterreceivesNone; by default the context is{"request": request}. -
Results are GraphQL results. A tool returns
{"data": ..., "errors": [...]}. Partial data comes back with its errors; a result with no data at all is a tool error. Arguments are coerced by GraphQL, so a wrong one comes back as GraphQL's own error message. -
Mask your resolvers' errors. An error reaches the client with the message it was raised with, as it does over HTTP, but here it lands in a model's transcript, where it is easier to pass on. The library's own errors leave out SQL and values; for exceptions your resolvers raise, add Strawberry's
MaskErrorsto the schema. Masking only the errors a resolver raised keeps GraphQL's own messages, which a client needs to correct its query:from strawberry.extensions import MaskErrors def mask_raised(error): return error.original_error is not None schema = orm.schema( query=Query, extensions=[lambda: MaskErrors(should_mask_error=mask_raised)], )
-
Authenticate it.
mcp_serveradds no authentication of its own, and warns when a server whose tools can change data, through a mutation operation orgraphqlwithallow_mutations=True, is built withoutauth=. Passtoken_verifier=andauth=, or serve it behind your own, before anyone else can reach it; behind your own, silence the warning withwarnings.filterwarnings("ignore", message="This MCP server's tools can change data"). Other keyword arguments, such asinstructions=andtools=, go toMCPServer, and the server it returns takes more tools with@server.tool(). -
Sync schemas need
sync=True. It runsschema.execute_syncin a worker thread and, with Django, closes stale connections around each call as Django's request handler would. Use it for Django's sync ORM, or whenever a resolver blocks. Without it the server awaitsschema.execute; if Django refuses withSynchronousOnlyOperation, it warns and reruns the query withexecute_syncfrom then on, but a mutation is not run twice: its result comes back with an error naming the root field Django stopped and the root fields that ran before it, whose changes stand.execute=takes over entirely: an async(query, variables, context, allowed) -> ExecutionResult. Your executor runsgraphql's operations on your schema, so the tool refuses a field that returns an interface or union your schema may resolve to a type the tool leaves out. -
Keep its DNS rebinding protection.
server.streamable_http_app()answers only requests whoseHostis127.0.0.1,localhostor[::1], on any port, and whoseOrigin, when sent, is one of those overhttp; others get 421 or 403, so a web page a local user opens cannot reach the server through a hostname it points at their machine. Passinghost=anything else turns the check off. To serve it under its own name, list that name:server.streamable_http_app(transport_security=TransportSecuritySettings(allowed_hosts=["mcp.example.com"], allowed_origins=["https://mcp.example.com"])), withTransportSecuritySettingsfrommcp.server.transport_security. -
Variables are bounded. A call's variables, for an operation's tool and for
graphqlalike, may hold at mostmax_variable_valuesvalues (default 10,000), counting each object, list and scalar, and nest at most 100 levels deep. They are measured in a worker thread before GraphQL coerces them. A call's arguments may hold no more between them, counted in that worker thread after GraphQL coerces them, with variables substituted and defaults filled in, wherever an alias or fragment repeats a field; and as it runs, again each time a list repeats a field, which fails before its arguments are coerced.
graphql_tool=True adds two tools: graphql_schema, which returns the schema as SDL, and graphql, which runs one operation the client writes. Pass a GraphQLTool to configure them:
from strawberry_orm.contrib.mcp import GraphQLTool, mcp_server
server = mcp_server(
schema,
operations=OPERATIONS, # optional with graphql_tool
graphql_tool=GraphQLTool(root_fields=["posts", "users"], max_depth=6),
context_getter=get_context,
)- Queries only, unless you opt in.
graphqlruns only queries, andgraphql_schemashows no mutations.allow_mutations=Trueshows and allows them, and marksgraphqldestructive. - Checked before it runs. An operation must be a single operation of at most
max_lengthcharacters (default 100,000),max_tokenstokens (default 2,000) andmax_depthlevels (default 10) that passes validation, may not define a fragment it does not use or one twice, and may select one field at most 20 times in one place of its result, fragments included, since validation compares every pair of such fields. It may also select at mostmax_fieldsfields (default 1,000), counting each alias and each fragment wherever it is spread. That counts the fields written, not the values returned: each list multiplies the fields below it by its length, so{ posts { comments { author { name } } } }is four fields but returns a name for every comment of every post. Keep the lists the schema returns paginated or capped. The length limit is checked before the operation is parsed and the token limit as it is parsed, so they bound the work of checking it too. The operation is parsed, checked and validated once, in a worker thread, andschema.executeruns that document, validating it only with the rules the schema's own extensions add, in a worker thread too. An extension such asParserCacheorValidationCachestill parses or validates it again on the event loop, as Strawberry does to report aMaxTokensLimiterthe operation is past. The schema's own extensions, such as Strawberry'sMaxAliasesLimiterandMaxTokensLimiter, apply when the operation executes, as for any request. - No introspection. An operation asking for
__schemaor__typeis refused, since it would describe the whole schema, mutations and fieldsroot_fieldsleaves out included.graphql_schemadescribes whatgraphqlmay use;__typenamestill works. - A schema that refuses introspection must say whether to share its SDL.
graphql_schemahands every MCP client the schema that Strawberry'sDisableIntrospection(orAddValidationRuleswithNoSchemaIntrospectionCustomRule) withholds from other clients, so with such an extensionmcp_server()raisesValueErrorunlessGraphQLTool(schema_tool=...)is given.schema_tool=Trueaddsgraphql_schemaall the same;schema_tool=Falseleaves it out, on any schema, andgraphqlthen takes operations written from what the client already knows. Withoutgraphql_schema, on a schema that refuses introspection, or withStrawberryConfig(disable_field_suggestions=True),graphql's errors suggest no names, whether for the operation or for its variables. root_fieldsnames the root fieldsgraphqlmay use, bare or qualified asQuery.postsandMutation.publish; withallow_mutations=True, a name both root types have must be qualified.graphql_schemashows only those and the types they reach, andgraphqlruns operations on that schema, so no interface, union ornodefield returns a type it leaves out. A type implementing an interface is reached only through a field that returns that interface, so in a Relay schemaNode's other implementations stay hidden unlessnodeis one of the root fields. A type keeps an interface there only while it has every field the interface shows, so a root type narrowed out of an interface does not implement it ingraphql_schema, and a type left with nothing to show is left out. A field that returns a root type, such as a payload'squery: Query, returns it narrowed the same way, and one that returns a root typegraphqlleaves out, such asMutationwhen it runs only queries, is left out too.descriptions=Falseleaves the schema's descriptions and deprecation reasons out ofgraphql_schema; deprecated fields and enum values are still marked@deprecated. To expose only part of the schema in the first place, build it withorm.schema(query=Query, tags="mcp").
To try it locally, python cli.py mcp serves a few operations on the seeded SQLAlchemy test schema at http://localhost:8421/mcp. Add --graphql-tool for the graphql and graphql_schema tools, and --allow-mutations to let graphql run mutations.
Passed to StrawberryORM.for_django() / for_sqlalchemy() / for_tortoise().
Shared options:
| Option | Default | Meaning |
|---|---|---|
default_query_limit |
None |
Caps each connection page (its size when first/last are not given), each generated root list, and each root list an @orm.field.eager() or orm.field.lazy(filters=…, order=…) resolver returns as a query, after its filter, order and scope_rows. Nested relation lists, and a resolver's own query on a field with no generated filter or order, are not limited. |
exclude_sensitive_fields |
True |
Excludes sensitive-looking fields from generated input/filter/order types. |
warn_sensitive |
True |
Warns when sensitive-looking fields are exposed on output types. |
warn_missing_scope |
True |
Warns when an @orm.type class has no scope_rows classmethod. STRAWBERRY_ORM_WARN_MISSING_SCOPE=0 turns it off when the option is not given. |
lazy_resolution |
"warn" |
"off", "warn", or "error" when a GraphQL relation field has no explicit resolver. Use orm.schema() for eager loading. |
enable_optimizer |
True |
When using orm.schema(), mount the query optimizer extension automatically. |
strict_hints |
True |
Raises at schema build when using=[...] names a relation the model does not have, or scope= is put on a field that is not a relation. Set False to ignore both instead. |
batch_relations |
True |
Collapses per-parent relation resolvers into one query per query shape. See Relation batching. |
max_filter_depth |
10 |
Caps filter nesting. Each not, each all / any / oneOf entry and each object hop is a level, the foreign-key shortcut included. |
max_filter_branches |
50 |
Caps the all / any / oneOf entries of one filter argument, counted across the whole filter, each reference to a variable included. |
max_in_list_size |
500 |
Caps the inList / notInList values of one filter argument, and two for each range, counted across the whole filter, each reference to a variable included. |
max_filter_text_length |
1000 |
Caps the characters of contains, startsWith and endsWith text, i forms included, across one filter argument and across a request's filters. A field resolved for many parents counts once. |
max_filter_value_length |
100000 |
Caps the characters of every value a filter binds, each reference to a variable counted, across one filter argument and across a request's filters. A field resolved for many parents counts once. |
max_order_entries |
10 |
Caps the entries in an order list. |
max_group_by_entries |
10 |
Caps the entries in a groupBy list. |
max_groups |
100 |
Refuses a connection whose groupBy makes more groups than this. |
max_group_key_rows |
100 |
Refuses an objects: group key holding more related rows than this. |
enable_regex_filters |
False |
Enables regex and iRegex string lookups. Raises ValueError on Tortoise, which has no regex lookup. |
max_regex_filters |
3 |
Caps the regex / iRegex lookups across one filter argument and across a request's filters. A field resolved for many parents counts once. |
max_regex_text_length |
256 |
Longest value a regex / iRegex lookup is tested on, in characters (bytes on MySQL); a longer value does not match, and not keeps it. |
to_query |
None |
to_query(result, info): turns what a field, payload or connection resolver returns into a query when it is one of your own query objects. See Your own query objects. |
Django-only:
| Option | Default | Meaning |
|---|---|---|
django_async_safe |
True |
Offloads sync ORM resolvers with sync_to_async(thread_sensitive=True) under async GraphQL. |
SQLAlchemy-only:
| Option | Default | Meaning |
|---|---|---|
dialect |
"postgresql" |
SQLAlchemy dialect. |
session_getter |
None |
Callable returning the session for the current request. |
filter_overrides |
{} |
Maps Python types to custom lookup input types. |
offload_sync_session |
False |
Under async execution, runs the library's own reads on a sync Session with sync_to_async(thread_sensitive=True) rather than on the event loop. See Async usage. |
field_order |
None |
field_order(model, names): the order a model's fields are listed in, given its column and relation names in mapper order (columns first). Names it leaves out follow the ones it returns. |
Every name below is documented with its signature in the API reference.
StrawberryORM, auto, make_ref_type, UpsertValidationError, UpsertNotFoundError, is_writing, PayloadPolicy, Ordering, DateGroupByInterval, DateGroupByOption, FieldDefinition, FieldHints, OptimizerExtension, OptimizerStore, UNSET, tags, TAGS_KEY, filter_field, order_field, group_field, aggregate_field, and the built-in lookup input classes from strawberry_orm.filters.
A blog API with users, posts, tags, and comments — covering types, relations, queryset scoping, optimizer hints, filters, ordering, object traversal, grouping, aggregation, mutations, ref lists, recursive node mutations, and the query optimizer:
# SQLAlchemy
import strawberry
from strawberry_orm import StrawberryORM, auto
orm = StrawberryORM.for_sqlalchemy(
dialect="postgresql",
session_getter=lambda info: info.context["session"],
)
# -- Filters, ordering, and grouping (register leaf models first) ------------
UserFilter = orm.filter(User)
UserOrder = orm.order(User)
TagFilter = orm.filter(Tag)
TagOrder = orm.order(Tag)
CommentFilter = orm.filter(Comment)
PostFilter = orm.filter(Post) # picks up author/tags/comments relations
PostOrder = orm.order(Post)
PostGroupBy = orm.group(Post) # group-by support for aggregation
# -- Types -------------------------------------------------------------------
@orm.type(User, filters=UserFilter, order=UserOrder)
class UserType:
id: auto
name: auto
email: auto
posts: list["PostType"]
@orm.type(Tag, filters=TagFilter, order=TagOrder)
class TagType:
id: auto
name: auto
@orm.type(Comment, filters=CommentFilter)
class CommentType:
id: auto
body: auto
@orm.type(Post, filters=PostFilter, order=PostOrder, group=PostGroupBy)
class PostType:
id: auto
title: auto
body: auto
is_published: auto
tags: list[TagType] = orm.field.eager(
lambda select, info: select.order_by(Tag.name)
)
comments: list[CommentType]
@orm.field.lazy
def author(self, info: strawberry.Info) -> UserType:
return self.author
@classmethod
def scope_rows(cls, select, info):
return select.where(Post.is_published.is_(True))
# -- Mutations ---------------------------------------------------------------
CreatePostInput = orm.input(Post, include=["title", "body", "author_id"])
CreateTagInput = orm.input(Tag, include=["name"])
TagRef = orm.ref(Tag, create=CreateTagInput, unlink=True, delete=True)
CreateNodeInput = orm.mutations.create_node_input(name="CreateNodeInput")
@strawberry.type
class Mutation:
@strawberry.mutation
def create_post(self, input: CreatePostInput) -> PostType:
post = Post(title=input.title, body=input.body, author_id=input.author_id)
...
return post
@strawberry.mutation
def set_post_tags(self, post_id: int, tags: list[TagRef]) -> PostType:
post = ...
orm.apply_ref_list(post, "tags", tags)
return post
@strawberry.mutation
def create_node(self, info: strawberry.Info, input: CreateNodeInput) -> bool:
... # authorize, then write it yourself
@strawberry.type
class Query:
users: list[UserType] = orm.field.eager()
posts: list[PostType] = orm.field.eager()
schema = orm.schema(query=Query, mutation=Mutation)# Filter posts by a related author's name, ordered by title
{
posts(
filter: {
all: [
{ field: { isPublished: { exact: true } } }
{ object: { author: { field: { name: { exact: "Alice" } } } } }
]
}
order: [{ field: { title: ASC } }]
) {
title
author { name }
tags { name }
}
}
mutation {
setPostTags(postId: 1, tags: [
{ update: { id: "2" } }
{ create: { name: "new-tag" } }
{ unlink: { id: "3" } }
{ delete: { id: "4" } }
]) {
tags { id name }
}
}
mutation {
createNode(input: {
post: {
title: "Hello"
body: "World"
author: { create: { name: "Alice", email: "alice@example.com" } }
tags: [{ create: { name: "python" } }]
}
})
}Bug reports and pull requests are welcome — see CONTRIBUTING.md for development setup, the test layout, and the backend parity rules.
MIT