Expose Managers via GraphQL¶
Managers with an Interface are registered during GeneralManager startup and receive generated query, mutation, and subscription fields based on their interface capabilities.
Query and update your first manager¶
Start with the Project from the quickstart, with AUTOCREATE_GRAPHQL = True and its migrations applied. You already have a generated API; no custom output type or resolver is needed for these operations.
Send this operation to the configured GraphQL endpoint:
query Projects {
projectList(orderBy: [{field: name}], page: 1, pageSize: 10) {
items { id name }
pageInfo { totalCount }
}
}
projectList returns a page. items contains the records you may read; pageInfo describes the result set. Copy an id from the response when you want to address that project. With the unchanged quickstart, Apollo is visible without login. After the permission tutorial, use an authenticated session for reads and an authorized editor for updates.
To rename one project, send a mutation with that ID in its variables:
mutation RenameProject($id: ID!) {
updateProject(id: $id, name: "Apollo launch") {
success
project: Project { id name }
}
}
For example, variables are {"id": "1"} if the query returned ID 1. Authenticate through your application's normal session or request integration; the request user supplies the write actor. The operation needs update permission, and normal HTTP authentication and CSRF handling still apply. The alias project: Project gives the generated Project payload field the response key project. A successful result contains success: true and the new name. A denied mutation reports a top-level GraphQL error; check errors before using the payload.
Choose the next GraphQL task¶
- Declare computed properties and query annotations.
- Use filters, ordering, and pagination to refine lists.
- Read partial updates for omission, nulls, and history comments.
- Use custom mutations for service operations beyond generated CRUD.
- Use output-only types when a calculated response needs a nested object shape.
- Review security when integrating a new client or custom resolver.
The remaining sections cover those additional contracts and integration cases.
Declare computed GraphQL properties¶
Use @graph_ql_property on a manager method with a return type hint. Access it as an attribute in Python (book.title_length), and select it as a field in GraphQL (titleLength with default camel-casing). The getter supplies the returned value; its return annotation supplies the GraphQL type.
| Option | Purpose |
|---|---|
filterable=True | Expose supported property filters in generated list queries. |
sortable=True | Allow the property in generated ordering options. |
query_annotation=... | Give a database bucket an ORM representation for filtering, exclusion, and sorting. |
is_identifier=True | Expose supported native key values as GraphQL ID; see identity properties. |
cache="run" | Default: reuse getter results inside the active run. |
cache="dependency" | Reuse getter results across runs with dependency tracking. |
cache="timeout", timeout=60 | Cache getter results for the configured number of seconds. |
cache="none" | Evaluate the getter on every access. |
warm_up=True | Enable proactive warm-up; requires dependency or timeout caching. |
Filtering and sorting default to disabled. Supplying query_annotation does not enable either flag, and does not change the property's output type or cache policy. A return type hint is mandatory even when an ORM expression has an output_field.
Use an ORM expression with query_annotation¶
For a database-backed manager, express the same calculation twice: once as Python for reading the property and once as a Django expression for querying it. For example, place this manager in a registered Django application and create its migration before using it:
from django.db import models
from django.db.models.functions import Length
from general_manager import GeneralManager, graph_ql_property
from general_manager.interface import DatabaseInterface
class Book(GeneralManager):
title: str
class Interface(DatabaseInterface):
title = models.CharField(max_length=200)
@graph_ql_property(
filterable=True,
sortable=True,
query_annotation=Length("title"),
cache="none",
)
def title_length(self) -> int:
return len(self.title)
Book.all().filter(title_length__gte=10) makes the database bucket annotate its queryset as title_length=Length("title") before applying the lookup. Book.all().exclude(title_length__lt=10) uses the same annotation for exclusion; Book.all().sort("-title_length") uses it for descending ordering. The annotation alias is the Python property name, not titleLength. Expression field paths such as "title" refer to fields on the underlying Django model, not arbitrary manager getters.
With the default generated names, a GraphQL query can use the property without knowing its SQL expression:
query LongBookTitles {
bookList(
filter: {titleLength_Gte: 10}
orderBy: [{field: titleLength, direction: DESC}]
pageSize: 20
) {
items { title titleLength }
pageInfo { totalCount }
}
}
Both the typed filter field and ordering enum use GraphQL's default camel-casing. See the generated schema for your application's exact names.
The annotation is applied when the property is used by filter(), exclude(), or sort(). Merely selecting titleLength does not apply the annotation. Reading book.title_length or resolving the output field still calls the Python getter through its configured cache; SQL annotations do not replace that getter or automatically supply its return value.
Start from a bucket for Python property queries: use Book.all().filter(...) and Book.all().exclude(...). The current ORM interface applies class-level Book.filter(...) and Book.exclude(...) arguments directly to the model queryset before constructing a bucket. A computed property such as title_length is not a model field, so those shortcuts can raise Django FieldError before its annotation is installed. Filtering real model fields first, then chaining a property filter on the returned bucket, also works. Generated GraphQL list filtering uses the bucket path.
Use a queryset callback¶
For query preparation that needs more than one expression, pass a callable instead. It receives the current Django QuerySet and must return a QuerySet that exposes the property name for the subsequent lookup or order:
from django.db.models import F, QuerySet
from django.db.models.functions import Length
def annotate_title_length(queryset: QuerySet) -> QuerySet:
return queryset.alias(_title_size=Length("title")).annotate(
title_length=F("_title_size")
)
# Alternative declaration inside Book, replacing the property above:
@graph_ql_property(
filterable=True,
sortable=True,
query_annotation=annotate_title_length,
cache="none",
)
def title_length(self) -> int:
return len(self.title)
Pass the function itself, without calling it. Unlike the expression form, GeneralManager does not automatically bind a callback's result to the property name: the callback must define title_length itself. Return the transformed queryset, not an expression, a list, or an aggregate dictionary. Each callback must return a QuerySet because the next callback receives its result. A non-queryset result from the last callback fails with InvalidQueryAnnotationTypeError in the database query path. An earlier non-queryset result can fail inside a later callback instead.
Build on the supplied queryset so existing restrictions remain intact; starting again from Model.objects.all() can discard filters and authorization constraints. Avoid evaluation and side effects in the callback. It is query construction, not a per-row resolver, and may run again for chained operations. The property cache does not cache this callback. Make each callback self-contained instead of relying on another property's annotation having already been installed.
Keep Python and SQL behavior aligned¶
GeneralManager stores the annotation metadata without validating that it matches the getter. Test both returned values and query membership/order. In particular:
- Use compatible types and explicit Django
output_fielddeclarations where needed for mixed arithmetic. The getter's return annotation does not set the SQL expression's type. - Match null handling, rounding, and case/collation behavior. A getter that treats
Noneas zero needs an equivalent SQL expression, for example usingCoalesce. - Account for relation joins and aggregation: a query annotation can change row multiplicity or grouping. Keep the resulting queryset appropriate for the manager's model.
- Do not reuse an existing model field name for a computed annotation alias. Django's annotation validation and database/backend restrictions still apply.
Without query_annotation, a database bucket evaluates supported property filters and sort keys in Python. Filtering collects matching primary keys; sorting builds a database ordering from the computed values. This can require evaluating many candidates before pagination and can cause additional queries inside the getter. An ORM annotation can reduce this work for selection and ordering, but does not eliminate the getter's cost when the property is returned to the client. If a multi-key sort includes a Python-only property, the database bucket sorts the combined keys in Python, using ORM annotation values for the annotated keys.
CalculationInterface does not execute query_annotation¶
query_annotation is consumed by DatabaseBucket, not by CalculationBucket. A calculation manager has input combinations rather than one Django queryset for its computed rows. Setting an annotation on its property stores the metadata, but the calculation bucket never invokes the callback or evaluates the ORM expression. This remains true when a calculation input happens to be a database-backed manager.
Use a Python getter for the calculated value and the filter/sort flags for its generated GraphQL controls:
from general_manager import GeneralManager, graph_ql_property
from general_manager.interface import CalculationInterface
from general_manager.manager import Input
class DoubleNumber(GeneralManager):
number: int
class Interface(CalculationInterface):
number = Input(int, possible_values=[1, 2, 3])
@graph_ql_property(filterable=True, sortable=True, cache="none")
def doubled(self) -> int:
return self.number * 2
values = [item.doubled for item in DoubleNumber.filter(doubled__gte=4)]
# [4, 6]
descending = [item.doubled for item in DoubleNumber.all().sort("-doubled")]
# [6, 4, 2]
Property filters/excludes instantiate calculation managers and read their properties through getattr; property sorting also uses Python values. Adding query_annotation would not change these results or move the work to SQL. The calculation path supports its own Python lookup set, not every Django lookup.
For large domains, narrow declared inputs before computing derived values, or move database-expressible work to a database-backed input manager and filter that source before constructing combinations. Cache expensive getters with an appropriate scope. If a result must itself support database-level annotations, model it through an appropriate database-backed interface. Automatically translating arbitrary calculation getters or input combinations into SQL is not provided by query_annotation.
Generated GraphQL calculation lists first narrow proven native scalar or manager-identity constructor inputs and freeze that exact requested domain. Row authorization and operand checks then run before deferred related-value or computed-property predicates, sorting, and pagination. Custom getters are not safe constructor constraints, and exclusion groups stay atomic. Keep that boundary when designing custom resolvers; see query-operand authorization.
Return structured GraphQL values¶
Use GraphQLType for a response value that needs a GraphQL object shape but does not need a manager identity, lifecycle, or root operation. Import the declaration at startup (normally from an application module imported during app initialization) so GeneralManager discovers it before building the schema. Concrete subclasses are automatically frozen dataclasses:
from __future__ import annotations
from dataclasses import field
from general_manager import GeneralManager, GraphQLType, graph_ql_property
from general_manager.measurement import Measurement
from your_app.managers import Task, User # application-specific registered managers
class ProjectHour(GraphQLType):
user: list[User]
total_hours: Measurement
task: Task
notes: str | None = None
tags: list[str] = field(default_factory=list)
class ProjectHoursSummary(GeneralManager):
@graph_ql_property
def project_hours(self) -> list[ProjectHour]:
return [
ProjectHour(
user=[user],
total_hours=Measurement(8, "h"),
task=task,
)
]
User and Task are application-defined GeneralManager subclasses in this illustrative example; replace the import with your registered manager module. The user and task values passed to ProjectHour must be produced by the owning property's application-specific calculation logic. GraphQLType only describes the nested response shape and does not fetch or inject those values.
No explicit @dataclass decorator is required. Standard dataclass defaults and field(default_factory=...) work, and construction is frozen after the instance is created. The declaration above becomes the GraphQL object ProjectHourType; it does not create a query, mutation, subscription, filter, capability field, or manager lifecycle. It is available only through a field that references it, such as projectHours in the example.
For scalar fields, the strict allowlist is str, bool, int, float, Decimal, datetime, date, and subclasses of those types. Unknown scalar-like classes are rejected and do not receive the legacy mapper's fallback to String. The other supported values are Measurement, registered managers, registered output types, and list[T], tuple[T, ...], or set[T]. Use T | None for nullable values. Required annotations become non-null GraphQL fields, while optional annotations become nullable fields; collection elements follow the same rule. Bare collections, every fixed-length tuple such as tuple[int, int], Any, Annotated[...], unresolved references, and multi-target unions are invalid output annotations and fail schema generation with a field-specific error. Only homogeneous variadic tuples written as tuple[T, ...] are supported.
The @graph_ql_property on the owning manager remains the authorization boundary. A nested manager field still uses that manager's normal GraphQL read permissions. Plain scalar fields and nested GraphQLType fields do not receive an independent permission check, so omit or pre-authorize sensitive values in the owning property.
The typed output-object recipe shows the same contract with a complete startup import, calculation property, and GraphQL query.
For flat native identities inside an output value, mark each dataclass field:
from dataclasses import field
from uuid import UUID
from general_manager import GraphQLType
class RecordProjection(GraphQLType):
record_key: int = field(metadata={"is_identifier": True})
related_keys: list[int] = field(metadata={"is_identifier": True})
optional_key: UUID | None = field(metadata={"is_identifier": True})
quantity: int
Return native values from the owning property: for example, RecordProjection(9007199254740993, [9007199254740993], None, 17). The fields expose ID!, [ID!]!, ID, and Int!; GraphQL returns identity strings and the numeric quantity. Keep the object-returning property's own identity flag unset. The field flag defaults to false and must be a boolean; it changes only explicitly marked native int/string/UUID fields and supported flat collections. Optional and element nullability, frozen values, defaults, permissions, and native annotations are preserved. Do not cast values to strings or annotate fields with graphene.ID; use native key annotations. Regenerate client types after opting in and keep IDs as opaque strings.
Declare manager relations¶
Annotate related fields with the manager class that should appear in generated GraphQL. GeneralManager also recognizes collection wrappers, optional values, and postponed annotations, so this pattern works when from __future__ import annotations is enabled:
from __future__ import annotations
from django.db import models
from general_manager import GeneralManager
from general_manager.bucket import Bucket
from general_manager.interface import DatabaseInterface
class User(GeneralManager):
name: str
class Interface(DatabaseInterface):
name = models.CharField(max_length=100)
class Project(GeneralManager):
owner: User | None
reviewer_list: Bucket[User]
class Interface(DatabaseInterface):
owner = models.ForeignKey(
User.Interface._model,
on_delete=models.SET_NULL,
null=True,
blank=True,
)
reviewer = models.ManyToManyField(User.Interface._model, blank=True)
attribute_types = Project.Interface.get_attribute_types()
assert attribute_types["owner"]["type"] is User
assert attribute_types["reviewer_list"]["type"] is User
DatabaseInterface registers both managers and derives relation metadata from the Django fields: owner maps directly to the foreign key, while the reviewer many-to-many field is exposed as reviewer_list. When the schema is built, owner becomes a single User object field and reviewer_list becomes a paginated relation-list field. The same manager target is used for nested relation filters, mutation relation inputs, and subscription identifiers. list[User], tuple[User, ...], set[User], Optional[User], "User", and "Bucket[User]" are also supported. Keep one manager target in a relation annotation; a union such as User | Team is ambiguous and does not produce manager-relation behavior.
For existing or generated Django models, GeneralManager uses the model's manager back-reference to recover the corresponding manager type. Register manager modules during startup as described in the installation guide, and then use the generated field names in queries, mutations, and subscriptions.
Expose manager-valued properties¶
Add these properties to the Project manager above to expose its owner as an object and as a native list, even though both names end in _list:
from general_manager import graph_ql_property
# Inside Project:
@graph_ql_property(cache="none")
def selected_list(self) -> User | None:
return self.owner
@graph_ql_property(cache="none")
def reviewers_list(self) -> list[User]:
return [self.owner] if self.owner is not None else []
Place the methods inside the class and register the manager at startup. Query selectedList { id } as an object and reviewersList { id } as a plain list; neither field accepts pagination arguments. tuple[User, ...] and set[User] also produce plain lists. An optional collection may return null, which is distinct from an empty list. The property read check runs before the getter; unreadable collection members are omitted. A Bucket[User] property named with _list, and generated reverse relations, retain paginated items and pageInfo. The cookbook shows a query for these shapes.
Filter by identifier¶
Actual ORM primary keys and raw scalar foreign-key references use GraphQL ID, and their outputs serialize as strings. Identifier equality and exact filters (id and id_Exact) use ID; membership (id_In) uses [ID]. This also applies to PKs with other names, such as code, and foreign-key aliases such as ownerId. Single manager relations remain object fields and collection relations remain paginated object fields.
Identity is derived from actual field metadata. An ordinary field named external_id or a calculation/request composite business input named id keeps its native scalar. Actual manager reference inputs use scalar IDs or structured inputs when the referenced manager has composite constructor inputs. Ordered comparisons such as id_Gt retain the native scalar and its hints, including BigIntScalar where configured.
Filter custom Excel identifiers¶
For a custom Excel interface, mark the scalar attributes that represent IDs in its metadata. For example, with a workbook containing sku and reference columns on Sheet:
from general_manager.interface import ExcelInterface
from general_manager.interface.base_interface import AttributeTypedDict
from general_manager.interface.excel import ExcelCharField, ExcelIntegerField
from general_manager.manager import GeneralManager
class TypedExcelRecord(GeneralManager):
class Interface(ExcelInterface):
sku = ExcelCharField(unique=True)
reference = ExcelIntegerField()
class Meta:
workbook = "data/identifiers.xlsx"
sheet = "Sheet"
header_row = 1
key = "sku"
@classmethod
def get_attribute_types(cls) -> dict[str, AttributeTypedDict]:
attributes = super().get_attribute_types()
attributes["sku"]["is_identifier"] = True
attributes["reference"]["is_identifier"] = True
return attributes
Expose the manager in the GraphQL schema and configure read permissions as for other managers. Equality and membership filters and exclusions use ID values; without an applicable constructor input, Excel converts them to the declared int, str, or UUID type. Keep client values as strings to preserve large integers and leading zeros. See the query recipe.
Configure UUID and string primary keys¶
The GraphQL scalar does not change the Python/database type or configure the manager constructor. Keep an explicit Input(UUID) or Input(str) for ORM keys that do not use the default integer input:
from uuid import UUID, uuid4
from django.db import models
from general_manager import GeneralManager
from general_manager.interface import DatabaseInterface
from general_manager.manager import Input
class UuidRecord(GeneralManager):
class Interface(DatabaseInterface):
input_fields = {"id": Input(UUID)}
id = models.UUIDField(primary_key=True, default=uuid4)
name = models.CharField(max_length=100)
class CodeRecord(GeneralManager):
class Interface(DatabaseInterface):
input_fields = {"id": Input(str)}
code = models.CharField(max_length=32, primary_key=True)
name = models.CharField(max_length=100)
CodeRecord exposes code: ID and code/code_Exact/code_In filters. Its detail query still accepts the constructor argument id: ID!, which addresses that model's code PK. UUID values remain UUID objects in Python; code values remain strings.
Declare native identity properties¶
Mark a property returning real keys explicitly, retaining its native Python annotation and cache configuration:
from django.db import models
from general_manager import GeneralManager, graph_ql_property
from general_manager.interface import DatabaseInterface
class Record(GeneralManager):
class Interface(DatabaseInterface):
id = models.BigAutoField(primary_key=True)
sequence = models.IntegerField(default=7)
@graph_ql_property(is_identifier=True, cache="none")
def record_key(self) -> int:
return self.id
@graph_ql_property(is_identifier=True)
def record_keys(self) -> list[int]:
return list(type(self).filter(id=self.id).values_list("id", flat=True))
@graph_ql_property
def external_id(self) -> int:
return self.sequence
The generated fields are recordKey: ID, recordKeys: [ID], and externalId: Int. UUID and string key properties use the same option with UUID and str annotations. Homogeneous tuples and sets, optional values, and optional elements are supported. Properties remain nullable. Do not mark business numbers or object/manager results as identities; nested collections, mixed unions, and unsupported native types fail schema generation with TypeError. A property name or an ORM query annotation alone does not select ID. Set filterable=True and configure backend filtering separately when needed. Python and Bucket projection values remain native.
After opting in, regenerate the schema and client types and update comparisons and cache keys to use strings. A scalar property previously returning the JSON number 7 now returns "7"; a list returns ["7"]. A key such as 2147483648, which previously exceeded GraphQL Int and produced an error, now serializes as "2147483648". See the query recipe for an executable selection.
Migrate existing clients¶
- Change affected variable declarations from
IntorStringtoID, and their list equivalents to[ID], keeping the intended nullability. Range variables and composite business inputs retain their native types. - Regenerate schema-derived client types after updating the schema.
- Update equality comparisons, selected-item state, and normalized cache keys to use returned ID strings consistently. An integer-backed ID now returns
"42", so comparing it with the number42will no longer match. - Keep IDs as opaque strings. Avoid
Number,parseInt, or other numeric coercion; large integers may lose precision, and UUID/string keys cannot be represented as numbers. - Check create-operation variables for required fields without real defaults.
NOT_PROVIDEDno longer appears as a schema default, so a declaration such as$budget: MeasurementScalarmust become$budget: MeasurementScalar!when the generated create argument is required, even if a value is supplied. - If an older schema exposed a business field named
idas anIDfilter, change equality and membership variables to its native scalar, such asIntand[Int]. The existing filter operators remain available.
The identifier filter concept and query patterns show requests using the updated declarations.
Filter calculation managers by manager input¶
Calculation managers expose manager-typed Input(...) fields as direct nested GraphQL relation filters. For example, this calculation accepts a Project manager input:
from datetime import date
from general_manager.interface import CalculationInterface
from general_manager.manager import GeneralManager, Input
from myapp.managers import Project
class ProjectCommercial(GeneralManager):
class Interface(CalculationInterface):
project = Input(Project)
target_date = Input(date)
Filter the generated list field with the nested manager's fields:
query ProjectCommercials($projectId: ID!) {
projectCommercialList(filter: {project: {id: $projectId}}) {
items {
project { id name }
targetDate
}
}
}
The GraphQL resolver flattens the nested input to the Python lookup project__id=<projectId> before calling the calculation bucket. Nested manager lookups such as {project: {name__startswith: "North"}} are flattened in the same way. This behavior applies when the calculation input metadata omits relation descriptors; explicitly declared relation metadata and custom lookup prefixes remain authoritative.
The same calculation filter contract applies when an input's possible_values returns a Python iterable such as list(Project.all()) or a GeneralManager bucket. Manager equality, _id, __in, and nested lookups are applied before generated relations are paginated, so each relation remains scoped to its parent. A cached calculation value does not widen that scope.
Declare typed calculation collections¶
Use a parameterized Input(list[T]) when one calculation input represents an ordered selection rather than one independent scalar choice. The declaration generates a native GraphQL list and keeps the selection's order and duplicates:
from general_manager.interface import CalculationInterface
from general_manager.manager import GeneralManager, Input
from myapp.managers import Employee
class WorkforceSummary(GeneralManager):
class Interface(CalculationInterface):
employees = Input(list[Employee], required=False)
values = Input(list[int], required=False)
The generated detail arguments are employeesId: [ID!] and values: [Int!]. Python construction requires an actual list; manager members can be instances, IDs, or constructor mappings. Omission and explicit null resolve to None, while [] is an explicit empty selection. GraphQL may apply its normal singleton-to-list coercion, but null elements are rejected. Required collections use Input(list[T]) and produce an outer non-null argument.
query Summary($employees: [ID!], $values: [Int!]) {
workforceSummary(employeesId: $employees, values: $values) {
employees { id name }
values
}
}
Use filter(field=selection) or filter(field__in=[selection, ...]) for whole selection comparisons; scalar __in behavior is unchanged and other collection lookups are unsupported. A manager-list output first checks the owning field's read permission, then omits members that fail their own manager-level read gate without reordering permitted duplicates. The collection-input cookbook shows a complete calculation and query.
Use measurements and large integers¶
Interface fields typed as Measurement are exposed with MeasurementScalar for inputs. Send measurements as strings with a magnitude followed by a Pint unit, for example "12.5 m/s" or "100 EUR". Invalid measurement strings fail during GraphQL input coercion with the same validation errors raised by Measurement.from_string().
mutation UpdateInventory($id: ID!, $price: MeasurementScalar!) {
updateInventory(id: $id, price: $price) {
success
}
}
Native fields marked with graphql_scalar="bigint" use BigIntScalar, as do range comparisons on identities with that hint. Identity outputs and equality filters use ID while retaining the native hint in metadata. BigIntScalar returns large integers as strings to avoid precision loss in JavaScript clients and accepts string or integer inputs. Boolean values are rejected explicitly, and other non-coercible values fail with a scalar coercion error. Float and Decimal values are accepted for compatibility but are truncated with Python int(...), so 1.9 becomes 1.
The low-level scalar mapper only maps concrete scalar classes. Higher-level schema generation unwraps optional fields and builds list fields before calling that mapper; direct calls with annotations such as Optional[int], list[int], or Annotated[int, ...] fall back to String.
Create a manager with a manual primary key¶
Generated ORM create mutations omit auto-increment keys. Editable manual PKs are accepted as ID, including a PK field named id. A PK without a default is required; a model default makes it optional. For the CodeRecord above:
mutation CreateCodeRecord($code: ID!, $name: String!) {
createCodeRecord(code: $code, name: $name) {
success
}
}
{"code": "CAT-042", "name": "Catalog entry"}
Create arguments retain literal model defaults. The NOT_PROVIDED sentinel and callable defaults are absent from the schema; schema construction never calls them. Omitting id when creating UuidRecord lets the ORM apply uuid4 at write time. Requiredness, model validation, and validation of explicit null remain enforced.
Disable selected generated mutations¶
Use a manager-level __graphql_mutations__ set or frozenset to expose only the generated CRUD operations your application needs. For example, keep generated create and delete but replace the broad generated update with a narrower custom mutation:
from decimal import Decimal
from typing import ClassVar
from django.db import models
from graphql import GraphQLResolveInfo
from general_manager import GeneralManager
from general_manager.api.mutation import graph_ql_mutation
from general_manager.interface import DatabaseInterface
from general_manager.permission.mutation_permission import MutationPermission
class QuotedPrice(GeneralManager):
__graphql_mutations__: ClassVar[set[str]] = {"create", "delete"}
class Interface(DatabaseInterface):
customer = models.CharField(max_length=100)
price = models.DecimalField(max_digits=12, decimal_places=2)
class CanChangePrice(MutationPermission):
__mutate__: ClassVar[list[str]] = ["isAuthenticated"]
@graph_ql_mutation(CanChangePrice)
def change_quoted_price(
info: GraphQLResolveInfo, quote: QuotedPrice, price: Decimal
) -> QuotedPrice:
return quote.update(price=price, creator_id=info.context.user.pk)
Import this module during startup as you would other manager and custom mutation declarations. The schema contains createQuotedPrice, deleteQuotedPrice, and changeQuotedPrice, but no generated updateQuotedPrice. The custom mutation accepts only the quote identifier and new price, so it cannot change customer. The Decimal annotation gives the new price an exact decimal input contract.
Omit __graphql_mutations__ to use the global generated CRUD default (all three supported operations unless configured otherwise). Use set() or frozenset() to hide all generated CRUD; do not use {}, which is a dictionary. Only the lower-case names "create", "update", and "delete" are valid. Subclasses inherit the allowlist and can replace the entire set; prefer assignment to mutating an inherited set in place.
The option is read during schema construction, not on each request. It does not remove already registered custom mutations or change generated read queries, interface write capabilities, Python create() / update() / delete(), or manager permissions. The custom mutation above still uses the manager's normal update-permission check. An allowlisted operation must also be supported by the interface to be generated.
Partially update a generated manager¶
Generated CRUD payloads use the manager class name as their result field: Project for this manager. The alias project: Project below gives the JSON response a lower-case project key. Custom @graph_ql_mutation functions instead derive a lower-case result field from their return type.
When an ORM interface supports update and the manager allows the generated operation, GeneralManager generates an update<ManagerName> mutation. The target argument remains id: ID!; writable fields cannot overwrite it, and primary keys are excluded from update payload fields. Each other editable field is optional. This makes it safe to change one field without re-sending the rest of the object:
mutation RenameProject($id: ID!) {
updateProject(id: $id, name: "Renamed") {
success
project: Project { id name score }
}
}
If score has a model default such as 7, the mutation above preserves the project's existing score. The same rule applies when a nullable variable is declared but omitted from the variables object:
mutation SetOptionalScore($id: ID!, $score: Int) {
updateProject(id: $id, score: $score) {
success
project: Project { id score }
}
}
With variables { "id": "42" }, score is omitted and remains unchanged. With { "id": "42", "score": null }, score is explicitly cleared when the field is nullable. Supplying a concrete value sets it, including a value equal to its model default. Create mutations keep their normal model-default behavior. See the mutation concept, the GraphQL query cookbook, and the API reference for the complete contract and error behavior.
Keep mutation controls out of client input¶
Generated create and update schemas reserve creator_id, ignore_permission, and history_comment for manager execution metadata. If an editable interface field uses one of those names, schema generation raises a reserved-control error; a relation alias such as creator is rejected when it normalizes to creator_id. Rename the field or make it read-only.
Do not send creatorId or ignorePermission as generated GraphQL arguments; they are undeclared and fail schema validation before the resolver runs. The resolver's runtime guard also rejects creator_id or ignore_permission kwargs with BAD_USER_INPUT before upload-token preflight, and checks again after relation normalization. The actor always comes from info.context.user. Use the generated historyComment argument when an audit comment is needed:
mutation RenameProject($id: ID!) {
updateProject(id: $id, name: "Renamed", historyComment: "Reviewed") {
success
project: Project { id name }
}
}
This is distinct from application code calling GeneralManager.update() directly, where trusted server-side callers may still supply the manager's execution metadata. See the GraphQL security concept, the mutation cookbook, and the API reference.
Query generated lists¶
Generated list fields accept the arguments that the manager metadata supports, including filter, exclude, orderBy, page, and pageSize. Filters use the same lookup names as buckets. filter and exclude may be GraphQL input objects or JSON object strings; malformed JSON and decoded JSON values that are not objects are treated as empty filters. Relation none filters are supported under filter, but not under exclude. Top-level list queries and generated relation-list fields always include nullable page and pageSize. Omitting both returns the complete authorized result with pageInfo.pageSize: null. Supplying either enables pagination and defaults the other to page 1 or size 10; explicit sizes above the default maximum of 100 are rejected. Configure GENERAL_MANAGER["GRAPHQL_DEFAULT_PAGE_SIZE"] and GENERAL_MANAGER["GRAPHQL_MAX_PAGE_SIZE"] with positive integers to change these server limits (default must not exceed maximum). A partial request-backed source cannot satisfy an unpaged query; supply explicit pagination for such a source. The same contract applies to generated groups. They include nullable filter and exclude only when a filter input type can be generated for the manager, and nullable typed orderBy only when sortable fields exist. For a database-backed list, pass predicates through the generated filter input. Native execution is an optimization and does not bypass row or field permissions. See the native list example and filter evaluation order.
Soft-delete managers also expose nullable includeInactive on top-level list queries, which defaults to false and switches fallback list loading from Manager.all() to Manager.filter(include_inactive=True) when true. That fallback applies only when the resolver returns None; other falsey bucket-like values are used as returned.
orderBy accepts an ordered list of typed objects such as [{field: name}, {field: date, direction: DESC}]. The field is required and the direction defaults to ASC; an empty list or null leaves existing order unchanged. The first key is primary and later keys break ties. Generated order enums expose a direct manager field as an order by that manager's identifier; for example, [{field: commercials}] orders projects by the related commercial ID. A directly related scalar is available through a one-hop key such as commercials__name. Collection relations and multi-hop paths such as commercials__owner__name are not exposed as sort options. Computed @graph_ql_property values on the related manager are also excluded; only sortable properties on the root manager are eligible. Top-level and generated relation-list fields use the same list-valued sort contract.
Preserve an exact authorized subset¶
When a custom resolver has already evaluated each candidate manager against an instance-level policy, keep the originating bucket and reconstruct the result with with_instances(). This preserves the bucket's backend-specific representation. Non-database buckets that retain full identification mappings, such as CalculationBucket, can preserve composite identifications without replacing them with an id__in lookup. DatabaseBucket is ID-based and reads each manager's identification["id"]:
from collections.abc import Callable
from typing import TypeVar
from general_manager.bucket import Bucket
from general_manager.manager import GeneralManager
ManagerT = TypeVar("ManagerT", bound=GeneralManager)
def authorized_subset(
bucket: Bucket[ManagerT],
can_read: Callable[[ManagerT], bool],
) -> Bucket[ManagerT]:
authorized = [manager for manager in bucket if can_read(manager)]
return bucket.with_instances(authorized)
The returned bucket contains exactly the managers that passed the policy. Pass the managers in the bucket's iteration order when the existing ordering must be retained. Database-backed buckets reconstruct a source-ordered ID subset; request-backed and calculation buckets materialize the supplied instances without re-running their remote request or calculation domain. Generated GraphQL list resolvers apply this contract automatically for row-level read authorization, so custom resolvers only need it when they own that policy step. See the bucket concept and the permission cookbook version.
query ActiveProjects($filters: ProjectFilterInput) {
projectList(filter: $filters, orderBy: [{field: name}], page: 1, pageSize: 20) {
items {
id
name
}
pageInfo {
totalCount
currentPage
totalPages
pageSize
}
}
}
For typed variables, use the generated input list form and add an outer ! only when the client requires the variable itself to be non-null. For example:
query SortedProjects($order: [ProjectOrderBy!]) {
projectList(orderBy: $order) {
items {
id
name
}
}
}
{
"order": [{"field": "commercials__name"}, {"field": "name"}]
}
Use a dedicated grouped field with a required groupBy argument:
query ProjectsByDescendingStatus {
projectGroups(groupBy: ["status"], orderBy: [{field: status, direction: DESC}]) {
items { status name }
pageInfo { totalCount }
}
}
Ordinary projectList returns original records and does not accept groupBy. Grouped items expose flat key and aggregate fields. Numbers sum, distinct text values join, booleans use any, and dates/times use their maximum. Null values are excluded; an all-null scalar returns null. A group's id is null unless selected as a key. Relation ID aliases retain a shared non-null ID or return null when references differ.
A grouped singular relation is exposed as a collection of distinct original managers, with both list and grouping operations:
query ProjectsByCommercial {
projectGroups(groupBy: ["commercials_id"]) {
items {
commercialsId
commercialsList {
items { id name }
pageInfo { totalCount }
}
commercialsGroups(groupBy: ["name"]) {
items { name }
pageInfo { totalCount }
}
}
pageInfo { totalCount }
}
}
Bucket-backed collections support the same pair recursively. Every nested collection has independent filtering, exclusion, ordering and pagination scoped to its parent. Plain List[GraphQLType] properties remain output lists with no query controls; use a CalculationInterface and bucket for queryable calculated collections.
Filtering and row authorization precede grouping. Grouping keys and ordering fields must be readable, and aggregate fields check all contributing members. Sorting supports eligible aggregate scalars before pagination. totalCount counts groups. Empty results have items: [] and totalCount: 0; nonpositive pagination inputs are rejected. Incomplete remote pages cannot be grouped as complete data. See the grouping contract.
Legacy wrapper fields are no longer generated: select keys and aggregates directly under items. Retrieve original records and their count through the ordinary list endpoint.
Subscribe to an authorized manager instance¶
Use the generated detail subscription with the same identification arguments as the manager's query and mutation fields:
subscription ProjectDetails($id: ID!) {
onProjectChange(id: $id) {
action
item { id name }
}
}
GeneralManager checks the request user's instance read permission before it evaluates selected properties or registers channel listeners. It checks again after deferred channel registration, before the initial snapshot, and before each later event. If the target is missing or unreadable during initial subscription setup, setup fails with a GraphQL error before a stream is returned. If a later check finds the target missing or unreadable, the detail stream completes without sending a null item or the queued action; any registered listeners and channel groups are cleaned up. Permission-backend failures use the normal GraphQL error path. Selected fields continue to use their own read rules, so a readable target can still return null for a denied field. See the subscription concept and GraphQL API reference for the lifecycle and compatibility contract.
Class-wide subscription permission checks¶
Class-wide subscriptions receive committed row-level events for any instance of the manager class. Before an identified event is yielded, GeneralManager rehydrates the manager and checks object-level read permission in an asyncio.to_thread worker using the user captured when the subscription starts. An unreadable or no-longer-existing object is suppressed, while an unexpected permission exception propagates through the subscription error path. Aggregate refresh events have no identification and yield item = null without this object-level check.
Protect subscription payload fields¶
Each selected normal, measurement, and stored-file field in a generated detail or class-wide subscription applies the manager's usual field-level read permission. For class-wide subscriptions, this happens after an identified event passes its object-level check. Configure a field-specific rule on the manager's Permission class as you would for a query:
from general_manager import GeneralManager
from general_manager.permission import AdditiveManagerPermission, register_permission
@register_permission("isStaff")
def is_staff(_instance, user, _config):
return bool(getattr(user, "is_staff", False))
class Project(GeneralManager):
name: str
internal_note: str
class Permission(AdditiveManagerPermission):
__read__ = ["isAuthenticated"]
internal_note = {"read": ["isStaff"]}
With a subscription such as the one in the field-permission recipe, an authenticated non-staff user receives name and internalNote: null. The denial is limited to that field; sibling fields and the event action still resolve, and the denied field's value is not accessed. Permission evaluation, value access, measurement conversion, and stored-file formatting for allowed subscription fields run together in an async-safe worker. This also keeps uncached foreign-key values to other GeneralManagers safe to load in the subscription worker. Query and mutation field resolution stays synchronous. See the subscription concept and GraphQL API reference for the full compatibility and error contract.
Expose authorization hints¶
Use GraphQL permission capabilities when frontend code needs business-oriented authorization hints, such as whether the current user can rename a project. These fields are advisory only; backend permissions still enforce all reads and writes.
from general_manager import GeneralManager
from general_manager.permission import AdditiveManagerPermission, object_capability
def can_rename_project(project, user):
return project.status == "draft" and user.is_authenticated
class Project(GeneralManager):
class Permission(AdditiveManagerPermission):
graphql_capabilities = (
object_capability("canRename", can_rename_project),
)
Query the generated capability object:
query {
projectList {
items {
name
capabilities {
canRename
}
}
}
}
For list-heavy checks, pass batch_evaluator= to object_capability(...). The list resolver warms capability values for the returned page only when capabilities is selected.
For permission-backed, mutation-backed, and current-user examples, see GraphQL permission capabilities.
Add a custom mutation¶
Use @graph_ql_mutation for synchronous service-style mutations that do not map directly to the generated create, update, or delete operations. The decorator registers the mutation as soon as the module is imported and returns the original function, so the function remains directly callable in tests.
This fragment assumes an imported Project manager with an editable status field. Define it in an application module imported during startup. The decorator checks mutation access; project.update() also enforces the manager's write policy using the request user and persists the change. Returning the updated manager exposes a lower-case project result field for this custom mutation.
from general_manager.api.mutation import graph_ql_mutation
from general_manager.permission.mutation_permission import MutationPermission
class CanArchiveProject(MutationPermission):
__mutate__ = ["isAuthenticated"]
@graph_ql_mutation(permission=CanArchiveProject)
def archive_project(info, project: Project) -> Project:
return project.update(
creator_id=info.context.user.pk,
status="archived",
)
Supported decorator forms are @graph_ql_mutation, @graph_ql_mutation(), @graph_ql_mutation(SomePermission), and @graph_ql_mutation(permission=SomePermission). Do not pass both a positional permission and permission=; the positional permission wins.
Annotate every argument except the parameter named info, and add a return annotation. info is skipped by name and can appear in any position, but conventionally comes first. Optional[T] creates a nullable argument, default values become Graphene defaults, and list[T] creates a list argument. GeneralManager arguments with no declared inputs or a single id input become ID; GeneralManager arguments with multiple interface inputs become generated nested input objects. Manager values are normalized before permission checks: existing instances are preserved, None stays None, mapping inputs construct Manager(**value), and non-mapping inputs construct Manager(value). For list[Manager] and List[Manager] arguments, each list item follows that same normalization. Other supported annotations use the same scalar/object mapping as generated GraphQL fields.
Return one type for a single output field, or a tuple of types for multiple output fields. Output field names are derived from the Python type name or type-alias name with a lower-case first letter, and every generated mutation also exposes success. Tuple return values are assigned to output fields in annotation order and must contain exactly one value per annotated output. A count mismatch is sanitized as INTERNAL_SERVER_ERROR; internal mismatch details are not exposed.
At execution time the wrapper normalizes arguments before permission checks and before calling the original function. A configured permission class receives permission.check(normalized_kwargs, info.context.user). Missing parameter annotations raise MissingParameterTypeHintError, missing return annotations raise MissingMutationReturnAnnotationError, invalid return annotations raise InvalidMutationReturnTypeError, and duplicate output field names raise DuplicateMutationOutputNameError.
The root mutation field uses snake_to_camel: the first underscore-delimited segment stays unchanged and later segments are title-cased. Registration is first-writer-wins for duplicate custom root fields. The payload type capitalizes the first character of that name; see payload type names for typed-client migration guidance.
At the decorator boundary, explicit GraphQLError instances are preserved, while ValidationError and PublicGraphQLError retain their intended public behavior. PermissionError returns only Permission denied. with code PERMISSION_DENIED. Every other ordinary Exception, including ValueError, returns An internal server error occurred. with code INTERNAL_SERVER_ERROR and an opaque errorId; server logs retain the original details and matching error_id for correlation. Migrate client-facing ValueError uses to PublicGraphQLError, or to ValidationError for validation.
Use the safe GraphQL mutation error recipe for a copy-ready resolver and client handler. The GraphQL API reference documents the exact error signatures, extensions, and compatibility behavior.
Accept structured mutation inputs¶
Annotate a custom mutation parameter with a GraphQLType subclass to accept an input object. The same declaration can be returned from a @graph_ql_property. This example uses application-specific managers and a service function to save a month's planning changes.
from datetime import date
from graphql import GraphQLResolveInfo
from general_manager import GraphQLType
from general_manager.api.mutation import graph_ql_mutation
from general_manager.measurement import Measurement
from general_manager.permission.mutation_permission import MutationPermission
from your_app.managers import EmployeeProjectPlan, Project, User
from your_app.services import save_planning
class PlanningAllocationChange(GraphQLType):
user: User
project: Project
planned_weekly_hours: Measurement
class CanSavePlanning(MutationPermission):
__mutate__ = ["isAuthenticated"]
@graph_ql_mutation(CanSavePlanning)
def save_employee_planning(
info: GraphQLResolveInfo,
month: date,
changes: list[PlanningAllocationChange],
deletions: list[EmployeeProjectPlan] | None = None,
) -> bool:
save_planning(
actor=info.context.user,
month=month,
changes=changes,
deletions=deletions,
)
return True
For managers identified by a single ID, the client supplies user and project as IDs and can omit the deletions list. GraphQL accepts the measurement as a string. The permission check and resolver receive PlanningAllocationChange instances with manager and Measurement values.
mutation {
saveEmployeePlanning(
month: "2026-11-01"
changes: [{user: "42", project: "17", plannedWeeklyHours: "12.5 h"}]
) {
success
}
}
For variables, declare $changes: [PlanningAllocationChangeInput!]! and $deletions: [ID!].
Global generated CRUD default¶
To make generated mutations opt-in across the application, configure Django settings:
# Add this entry to your existing GENERAL_MANAGER dictionary.
GENERAL_MANAGER = {
# ... existing settings ...
"GRAPHQL_MUTATIONS_ENABLED": False,
}
The setting defaults to True, preserving existing create, update and delete exposure when no manager allowlist is declared. It must be a boolean, not a string or integer. The shared settings resolver also supports the legacy GENERAL_MANAGER_GRAPHQL_MUTATIONS_ENABLED and GRAPHQL_MUTATIONS_ENABLED settings, with the dictionary entry taking precedence.
An explicit __graphql_mutations__ set or frozenset, including one inherited from a parent manager, replaces the global default. For example, __graphql_mutations__ = {"create", "update", "delete"} opts a manager into all three supported operations even when the global default is False; set() opts it out even when the default is True. A subclass can replace the entire inherited allowlist. Explicit None is invalid, not a reset to the default.
Configuration is read when the schema is built. Changing settings does not remove already registered fields: rebuild/restart the schema to apply changes. This option affects only generated CRUD exposure, not read queries, custom mutations, Python writes, or permission enforcement. Interface capabilities still limit which opted-in operations can be generated.
Bind parameters to a calculation list¶
Declare each series identifier as an Input with an enumerable domain and window or override values as CalculationParameter on the same CalculationInterface. Use filter to select series, and parameters to supply values to every selected calculation. For example, a manager with edition = Input(int, possible_values=(2026, 2027)) and end_month = CalculationParameter(date) can be queried as follows:
query {
parameterSeriesList(filter: {edition: 2026}, parameters: {endMonth: "2026-03-01"}) {
pageInfo { totalCount }
items { edition totals }
}
}
Register the manager at application startup and grant the caller read access as usual. Generated reverse calculation lists accept the same argument. The parameter input is required if any parameter is required; its required fields must also be supplied. Detail queries use flat arguments instead. Parameters are not filter, sort, or group keys. Applying a nonempty parameter input to an authorized, already materialized relation produces a GraphQL error; parameters do not bypass read permissions.
For a complete manager and Python binding example, see the series recipe. The concept and API reference describe semantics and compatibility.