Python Mixins — API Reference
ViewSetBase
The base of ImplMixin and of every operation mixin and LookupMixin. It holds the hooks every viewset has.
class ViewSetBase:
def error_field(self, context: Context, field: str, code: str) -> str: ...error_fieldreturns the key under which a field error of the viewset's endpoint goes intofield_errors.fieldis the error's key (''for the body or a non-field error; inbulk_create,bulk_update,bulk_partial_updateandbulk_destroythe part after the row's key, which is put in front of the result; a DjangoValidationErrorraised by aperform_*method or an action has no row's key).codeis the error's code before the package's field error codes apply:pydantic.<type>,django.<code>, a namespaced type as it is, orpydantic.custom_error. The default returnsfield;''puts the error on the form. It is synchronous. An exception it raises answers 500fastapi-viewsets.unhandled_error. See Field names.
ImplMixin
Abstract base, a ViewSetBase. Subclasses implement every perform_* method except perform_bulk_destroy, which has a default.
class ImplMixin(ViewSetBase, Generic[K, T], ABC):
async def perform_create(self, context: Context, data: T) -> T: ...
async def perform_bulk_create(self, context: Context, data: list[T]) -> list[T]: ...
async def perform_list(self, context: Context) -> ListRecords: ...
async def perform_retrieve(self, context: Context, pk: K) -> T: ...
async def perform_update(self, context: Context, pk: K, data: T, partial: bool = True) -> T: ...
async def perform_bulk_update(self, context: Context, records: dict[K, T], partial: bool = True) -> list[T]: ...
async def perform_destroy(self, context: Context, pk: K) -> dict[K, None]: ...
async def perform_bulk_destroy(self, context: Context, pk: list[K]) -> dict[K, ApiErrorBody | None]: ...context (a Context instance) is built by route_viewset from settings.viewsets_context_processors - see Architecture.
from fastapi_viewsets.list_query import ListRecordsListRecords is Iterable[TItem] | AsyncIterable[TItem]. Written bare — as perform_list and every pipeline stage write it — it means ListRecords[Any]: what a backend yields is its own row type, and records are T only once to_record has run over them.
The same module carries the two helpers the pipeline reads a source with. async materialize(records: ListRecords[TItem]) -> list[TItem] drains a lazy source when an in-memory stage needs a list and returns a list untouched; async take_page(records: ListRecords[TItem], offset: int, limit: int) -> tuple[list[TItem], bool] walks a lazy source only as far as the page it is cutting. Both are coroutines and hand back the item type they were given. The ListMixin.take_page hook below is the overridable stage of the same name and delegates to this one.
Operation mixins
CreateMixin [K, T]
POST /→ callsperform_create(context, data: T) -> T. Withpk_field_nameset onroute_viewset, the body leaves the primary key out or gives it as null, anddatais aTwithout it unlessTgives it a default.
BulkOnlyCreateMixin [K, T]
POST /bulk→ callsperform_bulk_create(context, data: list[T]) -> list[T]
BulkCreateMixin [K, T]
Combines CreateMixin + BulkOnlyCreateMixin.
ListMixin [T, TFilter=None]
async def list_items(
self,
context: Context,
fltr: Annotated[TFilter, Query()] = None,
sort: Annotated[str | None, Query(description=SORT_DESCRIPTION)] = None,
offset: Annotated[int, Query(ge=0, description=OFFSET_DESCRIPTION)] = 0,
limit: Annotated[int | None, Query(ge=1, description="Page size.")] = None,
cursor: Annotated[str | None, Query(description=CURSOR_DESCRIPTION)] = None,
x_list_shape: Annotated[str | None, Header()] = None,
) -> Union[list[T], PaginatedList[T], CursorPage[T]]: ...GET /→list_items, which builds aListQueryout of the parameters and hands it toget_list(context, query);get_listcallsperform_list(context)itself, as its first stage.sortis always exposed (column:asc,column:desc, comma-separated). Without it the list is ordered bydefault_sort; an emptysort=leaves it unordered. WhenTFilteris provided, its fields are exposed as individual query parameters; a sequence-typed field is read from a repeated key (?ids=1&ids=2). WithoutTFilterthe endpoint has no filter parameter.route_viewsetnarrows both the parameters and the return type per viewset:offsetsurvives only whenpaginatedis among the declared shapes,cursoronly whencursoris,limitwhen either is, and theX-List-Shapeheader only when more than one shape is declared. The return type becomes the single declared shape's model, or aUnionof exactly the declared ones.- The
plainshape discardslimitand answers unpaginated;cursoris read only by thecursorshape. - Where the header survives, it is typed as a
Literalof the declared shapes plusNone, so any other value is a 422 and never reaches the handler. Where it does not, a header sent anyway is ignored, whatever it names, and the endpoint answers in its one declared shape. - A cursor that does not decode against the current ordering and filters is a 400.
Class attributes:
list_shape: str | None = None— this endpoint's shape, one of"plain","paginated","cursor".Nonetakessettings.default_list_shape, which is"plain".list_shapes: tuple[str, ...] | None = None— shapes a client may ask for withX-List-Shape.Nonemeans the default one only.default_page_size: int = 100—limitwhen a paged shape is asked for without one.max_page_size: int = 1000— ceiling onlimit.limitis at least 1 andoffsetat least 0; a request outside that is a 422.pk_field_name: str = "id"— appended to the cursor's ordering so every key tuple is unique.DjangoORMViewSetsupplies the model's own primary key instead.default_sort: str | None = None— the ordering of a request that sends nosort, in thesortparameter's syntax ("name:asc","category:asc,score:desc").route_viewsetpublishes it as thesortparameter's default in the schema, which the TS client'sdefaultSort()reads, and raisesValueErrorfor an empty entry, a direction other thanasc/desc, or a column the response model has neither a field nor a computed field for (check_declared_sort). It also orders a directlist_itemscall withoutsort;get_listwith aListQuerybuilt by hand takes the query'ssortas given.nulls: str = "first"— which end NULLs sit at when sorting ascending,"first"or"last".nulls_first: bool— property,self.nulls != "last".resolve_shapes() -> tuple— classmethod returning(default shape, shapes allowed); the default is always first in the allowed tuple.
Pipeline hooks, overridable one at a time — see the list pipeline for what pushing a stage into a backend involves:
get_list(context: Context, query: ListQuery) -> Any— the pipeline as a whole:perform_list→apply_filter→apply_sort→apply_pagination.apply_filter(context: Context, query: ListQuery, records: ListRecords) -> ListRecords— default applies the declared filters plus the cursor predicate, and delegates a hand-written filter model tofilter_list.apply_sort(context: Context, query: ListQuery, records: ListRecords) -> ListRecords— default delegates tosort_list.land(query: ListQuery, records: ListRecords) -> list— materialises the source and converts it withto_record. Idempotent; every in-memory stage goes through it.apply_pagination(context: Context, query: ListQuery, records: ListRecords) -> list[T] | PaginatedList[T]— returns aCursorPage[T]for thecursorshape, aPaginatedList[T]whenquery.limitis set, and the landed list otherwise.take_page(query: ListQuery, records: ListRecords) -> tuple[list, bool]— one page and whether anything follows it; the default readslimit + 1rows starting atoffset.count_records(context: Context, query: ListQuery, records: ListRecords) -> int | None— default islen(records)for a list or tuple andNonefor anything else, and alwaysNonefor thecursorshape.to_record(raw: Any) -> T— synchronous, identity by default. Must tolerate an already-converted record.
In-memory hooks:
filter_list(fltr: TFilter, records: list[T]) -> list[T]— post-filter hook with no default implementation; it returnsNone, whichapply_filterreads as "unfiltered" and answers with the records as they stand.sort_list(sort: SortState, records: list[T]) -> list[T]— post-sort hook. Default is a stable multi-key in-memory sort in the order ofcompare_in_order, strings by the keys ofcollation_for, placing NULLs wherenullssays.collation: Collation— class attribute, defaultget_collation(). The collationcollation_forreturns.async collation_for(context: Context | None, column_name: str) -> Collation— the collation ofcolumn_name's strings in the defaultsort_listand the in-memory cursor predicate. Default:collation.contextis theget_listcontext,Nonewhensort_listruns outsideget_list. Non-string values andNonedo not reach the collation. For the primary key column a string's raw value follows its key.DjangoORMViewSet.collation_forreturns code point order for its in-memory fallback. See Text order.
Collations (fastapi_viewsets.collation)
Collation—Protocol(runtime-checkable) withsort_key(text: str) -> Any. Any object with that method is a collation; keys of one collation compare with each other.get_collation(locale: str | None = None, on_mismatch: Literal["use", "warn", "fallback"] = "warn") -> Collation—None: the default collation, case-insensitive (str.casefold) with digit runs of up to 640 digits by value; key(parts, text). A locale: an ICU collator oficu.Locale.createCanonical(locale)withNUMERIC_COLLATIONon, one per thread; key(collator.getSortKey(text), text). Needs theicuextra; without PyICU it returns the default collation with aCollationWarning. A mismatch is a valid ICU locale that is root ("") while the canonical locale's language is not empty:"use"uses ICU's collation,"warn"uses it with aCollationWarning,"fallback"returns the default collation with aCollationWarning. One instance per(locale, on_mismatch), created under a lock; its warning is issued at creation. RaisesValueErrorfor anotheron_mismatch, and with PyICU for a locale ICU cannot read or whose canonical language is empty unless it is""or has the languagerootorund.CollationWarning—UserWarningsubclass.
PaginatedListMixin [T, TFilter=None]
ListMixin with list_shape = "paginated". GET / → PaginatedList[T], taking offset and limit.
CursorListMixin [T, TFilter=None]
ListMixin with list_shape = "cursor". GET / → CursorPage[T], taking cursor and limit.
RetrieveMixin [K, T]
GET /{pk}→ callsperform_retrieve(context, pk: K) -> T
UpdateMixin [K, T]
PUT /{pk}→ callsperform_update(context, pk, data, partial=False) -> TPATCH /{pk}→ callsperform_update(context, pk, data, partial=True) -> T. The body has every field ofToptional and no primary key;datais aTwhosemodel_fields_setnames the fields the body stated.
BulkOnlyUpdateMixin [K, T]
PUT /bulk→ callsperform_bulk_update(context, records, partial=False) -> list[T]PATCH /bulk→ callsperform_bulk_update(context, records, partial=True) -> list[T], each record asPATCH /{pk}passesdata.
BulkUpdateMixin [K, T]
Combines UpdateMixin + BulkOnlyUpdateMixin.
DestroyMixin [K, T]
DELETE /{pk}→ callsperform_destroy(context, pk: K) -> dict[K, None]; answers{pk: null}, 404fastapi-viewsets.not_foundfor a missing record
BulkOnlyDestroyMixin [K, T]
DELETE /bulk→ callsperform_bulk_destroy(context, pk: list[K]) -> dict[K, ApiErrorBody | None]; answers 200 keyed by pk:nullfor a deleted record, the failure'sApiErrorBodyotherwiseImplMixin.perform_bulk_destroy(default): callsperform_destroyfor each distinct key; anHTTPException, aRequestValidationErroror Django'sValidationErrorbecomes that key'sApiErrorBody, any other exception propagates
BulkDestroyMixin [K, T]
Combines DestroyMixin + BulkOnlyDestroyMixin.
Sort types
class SortDirection(str, Enum):
asc = "asc"
desc = "desc"
class SortStateColumn(BaseModel):
column_name: str # serialises as columnName (camelCase) via model_dump(by_alias=True)
direction: SortDirection = SortDirection.asc
SortState = list[SortStateColumn]parse_sort_param(sort_csv: str | None) -> SortState — parses the sort query string into a SortState. Format: "name:asc,score:desc"; a bare column name means ascending. Entries with an unknown direction are skipped.
check_declared_sort(sort_csv: str, model: Any = None) -> SortState — parses a declared default_sort and raises ValueError for an empty entry, an unknown direction, and, when model is a pydantic model, a column that is neither a field nor a computed field of it. route_viewset calls it with the response model.
SORT_DESCRIPTION: str — the sort parameter's description on every list endpoint.
OFFSET_DESCRIPTION: str, CURSOR_DESCRIPTION: str — the descriptions of offset and cursor. route_viewset replaces the description of limit with one stating the viewset's default_page_size and max_page_size.
LookupMixin [TLookupFilter=LookupFilter, TLookupItem=LookupItem]
GET /lookup→get_lookup(context, query: ListQuery) -> list[TLookupItem], wherequery.fltris the request'sTLookupFilter, orNonewhen no field of it is set. Its stages:perform_lookup(context) -> ListRecords— abstract; the source, lazy or not, ordered by group, then by text. The endpoint answers in this order; no stage reorders it.apply_lookup_filter(context, query, records) -> ListRecords— runs whenquery.has_filterand the"filter"stage is not marked applied. The default filters converted items in memory: by the declaration of amake_filter_modelfilter model, otherwise withfilter_lookup.filter_lookup(fltr: TLookupFilter, items: list[TLookupItem]) -> list[TLookupItem]— in-memory hook of a hand-written filter model; the default keeps items whosetitlecontainsfltr.q, ignoring case, and whosestr(pk)equals the string of an entry offltr.ids. A field that isNonedoes not filter.to_lookup_item(raw) -> TLookupItem— row conversion; identity by default.land_lookup(query, records) -> list[TLookupItem]— materialises the source and converts it, once per request.
- The response model is
list[TLookupItem].
class LookupItem(BaseModel):
group: Any = None
pk: object
title: str
icon: str | None = None
class LookupFilter(BaseModel):
q: str | None = None
ids: list[int | str] | None = Noneids is read from a repeated query key (?ids=1&ids=5) and documented in OpenAPI as an array of integers or strings.
Combined viewset mixins
ReadOnlyViewSetMixin [K, T]
Inherits: ListMixin[T], RetrieveMixin[K, T]
ViewSetMixin [K, T, TFilter=None]
Inherits: CreateMixin, ListMixin, RetrieveMixin, UpdateMixin, DestroyMixin
BulkViewSetMixin [K, T, TFilter=None]
Inherits: BulkCreateMixin, ListMixin, RetrieveMixin, BulkUpdateMixin, BulkDestroyMixin
NotFoundError
from fastapi_viewsets.exceptions import NotFoundError
raise NotFoundError(pk)
# HTTP 404: {"detail": "Item with pk <pk> not found", "detail_code": "fastapi-viewsets.not_found", "detail_params": {"pk": <pk>}, "field_errors": {}}