Skip to main content

yandex-drf-mixins

Typed reusable components for Django REST Framework and ADRF.

The library provides several independent groups of mixins:

  • DRF and ADRF ModelViewSet base classes, action-specific serializer selection, and create/update/upsert responses rendered with a retrieve serializer;
  • query-parameter and request-body serialization and validation;
  • synchronous and asynchronous limit/offset pagination with ?all=true support;
  • URL and API request test mixins that check status codes, JSON contracts, error codes, and SQL query counts.

Components can be used independently or as a coherent set through BaseModelViewSet and ABaseModelViewSet.

Installation

pip install yandex-drf-mixins

ADRF is an optional dependency:

pip install 'yandex-drf-mixins[adrf]'

Supported versions:

  • Python 3.10–3.15;
  • Django 4.0–6.1;
  • Django REST Framework 3.14–3.18;
  • ADRF 0.1.7+ within the 0.1.x series.

The CI matrix uses only combinations supported by the upstream projects. In particular, Django 6.0+ requires Python 3.12+, Django 6.1 is used for Python 3.15, and ADRF requires Django 4.1+. Django 4.0 therefore remains supported for the synchronous DRF components only.

The package includes a py.typed marker, so its public API types are available to mypy and other PEP 561-compatible type checkers.

Internationalization

The package provides English source messages and Russian translations for its user-facing API errors and schema descriptions. Add the package to Django's application registry so Django can discover the bundled translation catalog:

INSTALLED_APPS = [
    # ...
    "yandex_drf_mixins",
]

The active translation follows Django's standard LANGUAGE_CODE, locale middleware, and translation.override() behavior. English remains the fallback when no supported translation is active.

Quick start

Add two mixins to a regular APITestCase:

from rest_framework.test import APITestCase

from yandex_drf_mixins.testing import GenericRequestMixin, UrlNameMixin


class CourseListTestCase(UrlNameMixin, GenericRequestMixin, APITestCase):
    URL_NAME = "api:course-list"

The route is then resolved by name, while the request and routine assertions fit into a single method call.

LMS test examples

User setup, authentication, and factory data are omitted because they are application-specific and identical with or without this library.

LMS: test a paginated list

This example is adapted from LMS tag tests. The domain-specific build_expected() helper is omitted because it is unchanged by the library.

class TagListTestCase(UrlNameMixin, GenericRequestMixin, APITestCase):
    URL_NAME = "api:tag-list"

    def test_list(self):
        expected = self.build_expected(self.tags)

        self.list_request(
            url=self.get_url(),
            expected=expected,
            num_queries=4,
        )

list_request() checks:

  • HTTP 200;
  • the standard DRF pagination structure: count, next, previous, results;
  • the value of count;
  • object IDs and their order;
  • the complete JSON representation of every object;
  • exactly four SQL queries.
Without the library: the same list test written manually
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase


class TagListTestCase(APITestCase):
    def test_list(self):
        expected = self.build_expected(self.tags)
        url = reverse("api:tag-list")

        with self.assertNumQueries(4):
            response = self.client.get(url, format="json")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.data.keys(),
            {"count", "next", "previous", "results"},
        )
        self.assertEqual(response.data["count"], len(expected))
        self.assertEqual(
            [item["id"] for item in response.data["results"]],
            [item["id"] for item in expected],
        )
        self.assertListEqual(response.data["results"], expected)

LMS: test creation and a serializer error code

expected may be a function of the response, which is useful for generated IDs or timestamps. DRF errors can be checked by their stable ErrorDetail.code values instead of localized messages. Implementations of build_expected() and build_expected_errors() are omitted.

class TagCreateTestCase(UrlNameMixin, GenericRequestMixin, APITestCase):
    URL_NAME = "labapi:tag-create"

    def test_create(self):
        tag = TagFactory.build()

        self.create_request(
            url=self.get_url(),
            data={"name": tag.name},
            expected=lambda response: self.build_expected(tag, response),
            num_queries=5,
        )

    def test_duplicate_name(self):
        self.create_request(
            url=self.get_url(),
            data={"name": "existing-tag"},
            status_code=400,
            check_errors=True,
            expected=self.build_expected_errors(),
            num_queries=2,
        )
Without the library: creation and error checks written manually
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase


class TagCreateTestCase(APITestCase):
    def test_create(self):
        tag = TagFactory.build()
        url = reverse("labapi:tag-create")

        with self.assertNumQueries(5):
            response = self.client.post(
                url,
                data={"name": tag.name},
                format="json",
            )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertDictEqual(
            response.data,
            self.build_expected(tag, response),
        )

    def test_duplicate_name(self):
        url = reverse("labapi:tag-create")

        with self.assertNumQueries(2):
            response = self.client.post(
                url,
                data={"name": "existing-tag"},
                format="json",
            )

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        expected_errors = self.build_expected_errors()
        self.assertEqual(response.data.keys(), expected_errors.keys())
        self.assertEqual(
            response.data["name"][0].code,
            expected_errors["name"][0],
        )

update_request(), partial_update_request(), and delete_request() work the same way. Tests contain only endpoint-specific data, while requests and repeated assertions remain in the library.

API structure

Public components are separated by execution model:

from yandex_drf_mixins.drf import BaseModelViewSet
from yandex_drf_mixins.adrf import ABaseModelViewSet
from yandex_drf_mixins.schema import DJANGO_4XX_ERROR_JSON_SCHEMA
from yandex_drf_mixins.testing import GenericRequestMixin, UrlNameMixin
  • yandex_drf_mixins.drf contains synchronous DRF components;
  • yandex_drf_mixins.adrf contains ADRF components, with asynchronous classes prefixed by A;
  • yandex_drf_mixins.schema contains shared JSON Schema and OpenAPI contracts;
  • yandex_drf_mixins.testing contains API test mixins;
  • yandex_drf_mixins.base is internal and must not be imported by applications.

Testing API

UrlNameMixin

Set URL_NAME and use:

  • get_url_name() to return the route name and optionally select it dynamically;
  • get_url(*args, **kwargs) to call Django reverse();
  • assertURLNameEqual(url, base_url=None, args=None, kwargs=None) to check that a named route matches the expected URL.
class CourseDetailTestCase(UrlNameMixin, APITestCase):
    URL_NAME = "api:course-detail"

    def test_url(self):
        self.assertURLNameEqual(
            "courses/{}/",
            args=(self.course.id,),
            base_url="api/v1/",
        )

GenericRequestMixin

Common request helper arguments:

  • expected: expected JSON or a response -> expected callable;
  • status_code: expected status, defaulting to 200, 201 for create, and 204 for delete;
  • num_queries: expected SQL query count; None disables the check;
  • check_errors=True: recursively compare DRF error codes;
  • validate_4xx_response: validate Django/DRF 4xx response bodies against the library error JSON Schema; pass False to opt out for a specific request;
  • data: JSON request body.

Available methods:

Method Default HTTP Purpose
list_request() GET Check a list and optional DRF pagination
detail_request() GET Check one object
create_request() POST Check creation, expecting 201 by default
update_request() PUT Check a full update
partial_update_request() PATCH Check a partial update
delete_request() DELETE Check deletion, expecting 204 by default
make_request() configurable Perform any supported request scenario
assert_errors() — Recursively compare ErrorDetail structures and codes

Additional list_request() arguments:

  • pagination=True: expect count/next/previous/results;
  • count: expected total size, including a correct count=0 check;
  • check_ids=True: compare object IDs;
  • only_ids=True: limit comparison to IDs;
  • check_order=False: compare without considering order.

In synchronous tests, an explicit num_queries uses Django's native assertNumQueries(). The check is unreliable inside an event loop, so it is ignored there with a RuntimeWarning. Pass num_queries=None when SQL budgets are intentionally not checked.

Django/DRF 4xx response validation

A valid Django/DRF error response is a list or object whose leaves are strings; nested lists and objects are supported. The validator ignores responses outside the 400–499 range.

Validate responses in tests

GenericRequestMixin validates every 4xx response body by default. This schema check is independent from check_errors=True: schema validation checks the response structure, while check_errors compares stable ErrorDetail.code values.

from rest_framework import status
from rest_framework.test import APITestCase

from yandex_drf_mixins.testing import GenericRequestMixin


class CourseDetailTestCase(GenericRequestMixin, APITestCase):
    def test_missing_course(self):
        self.detail_request(
            "/api/courses/404/",
            status_code=status.HTTP_404_NOT_FOUND,
            check_errors=True,
            expected={"detail": "not_found"},
        )

Pass validate_4xx_response=False only when a particular endpoint intentionally uses a different response contract:

self.make_request(
    "/legacy-endpoint/",
    status_code=status.HTTP_400_BAD_REQUEST,
    validate_4xx_response=False,
)

Use assert_django_4xx_response(response) to perform the same strict check without the request helpers:

from yandex_drf_mixins.drf import assert_django_4xx_response

response = self.client.post("/api/courses/", data={})
assert_django_4xx_response(response)

Validate production responses per view

Add ValidateDjango4xxResponseMixin before the DRF view or viewset class in the inheritance list. Only views that include the mixin are validated.

Strict mode is the default: an invalid 4xx body raises AssertionError from finalize_response(). Use it when an invalid error contract must fail the request immediately:

from rest_framework.viewsets import ModelViewSet

from yandex_drf_mixins.drf import ValidateDjango4xxResponseMixin


class CourseViewSet(ValidateDjango4xxResponseMixin, ModelViewSet):
    pass

ADRF views use the equivalent async namespace mixin:

from adrf.viewsets import ModelViewSet

from yandex_drf_mixins.adrf import AValidateDjango4xxResponseMixin


class AsyncCourseViewSet(AValidateDjango4xxResponseMixin, ModelViewSet):
    pass

For an observation period in production, use soft mode. It logs the schema violation with the HTTP status, JSON path, reason, and response body, then returns the original 4xx response unchanged:

from rest_framework.viewsets import ModelViewSet

from yandex_drf_mixins.drf import ValidateDjango4xxResponseMixin


class CourseViewSet(ValidateDjango4xxResponseMixin, ModelViewSet):
    raise_django_4xx_response_validation_error = False

validate_django_4xx_response_decorator provides the same behavior for synchronous request methods. ADRF users can wrap asynchronous methods with avalidate_django_4xx_response_decorator from yandex_drf_mixins.adrf.

The public DJANGO_4XX_ERROR_* constants are available from yandex_drf_mixins.schema for publishing the corresponding OpenAPI schemas, examples, and references. They are shared by the DRF and ADRF validators rather than re-exported from either execution-model namespace.

Action-specific serializers

ActionSerializerMixin

Select a serializer by self.action:

from yandex_drf_mixins.drf import ActionSerializerMixin


class CourseViewSet(ActionSerializerMixin, ModelViewSet):
    serializer_class = CourseSerializer
    serializer_classes = {
        "list": CourseListSerializer,
        "retrieve": CourseDetailSerializer,
        "create": CourseWriteSerializer,
    }

get_serializer_class() returns the action-specific class or falls back to serializer_class. get_retrieve_serializer() always selects the retrieve serializer and adds the regular viewset serializer context. The same ActionSerializerMixin is exported from both drf and adrf.

Write serializer input, retrieve serializer output

Synchronous mixins

  • CreateWithRetrieveModelMixin validates the input serializer, calls perform_create(), and renders the retrieve serializer;
  • UpdateWithRetrieveModelMixin supports PUT/PATCH, calls perform_update(), clears the prefetch cache, and renders the retrieve serializer;
  • UpdateOrCreateWithRetrieveModelMixin updates an existing object or switches the action to create after Http404 and creates a new one;
  • Django ValidationError is converted to DRF ValidationError with exception chaining preserved.
from yandex_drf_mixins.drf import BaseModelViewSet


class CourseViewSet(BaseModelViewSet):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer
    serializer_classes = {
        "create": CourseWriteSerializer,
        "update": CourseWriteSerializer,
        "partial_update": CourseWriteSerializer,
        "retrieve": CourseDetailSerializer,
    }

Asynchronous counterparts

  • ACreateWithRetrieveModelMixin: acreate(), acreate_with_retrieve(), and aperform_create();
  • AUpdateWithRetrieveModelMixin: aupdate(), apartial_update(), aupdate_with_retrieve(), apartial_update_with_retrieve(), and aperform_update();
  • AUpdateOrCreateWithRetrieveModelMixin: aupdate_or_create().

The default aperform_create() and aperform_update() implementations call await serializer.asave(). After aperform_create(), the serializer must have an instance, otherwise the library raises ImproperlyConfigured. Asynchronous serializer data is read through the native adrf.mixins.get_data() helper.

Protected deletion

DeleteProtectedModelMixin

The synchronous mixin converts Django ValidationError and ProtectedError into DRF errors. Protected-relation text is configured through class attributes:

class CourseViewSet(BaseModelViewSet):
    protected_error_message = "Course cannot be deleted: %(object_name)s exists"
    protected_object_default_name = "related data"
    protected_objects_limit = 1

protected_objects_limit limits the number of protecting object names in the message. It defaults to 1; None includes all names. protected_object_default_name is used when ProtectedError has no objects. These settings are shared by synchronous and asynchronous mixins.

ProtectedError is returned as one ErrorDetail, not a one-element list.

ADeleteProtectedModelMixin

The asynchronous version provides adestroy() and aperform_destroy(). Its default implementation calls await instance.adelete() and handles ValidationError and ProtectedError in the same way.

Query-parameter and request-body validation

DRF

from rest_framework.views import APIView
from yandex_drf_mixins.drf import SerializeGetParamsViewMixin


class CourseSearchView(SerializeGetParamsViewMixin, APIView):
    params_serializer_class = CourseSearchParamsSerializer

    def get(self, request):
        params = self.validated_params
        return Response(search_courses(**params))
  • SerializeGetParamsViewMixin serializes request.query_params;
  • SerializePostParamsViewMixin serializes request.data;
  • SerializeParamsBaseViewMixin provides the common params_serializer and validated_params properties for custom parameter sources;
  • params_serializer_class selects the serializer;
  • params_raise_exception controls is_valid(raise_exception=...);
  • params_serializer_many=True collects query parameters into a list of objects;
  • params_serializer is validated on access; both it and validated_params are evaluated lazily and cached.

ADRF

ASerializeParamsBaseViewMixin, ASerializeGetParamsViewMixin, and ASerializePostParamsViewMixin use the same configuration contract but expose the validated serializer through await aparams_serializer() and its data through await avalidated_params():

class AsyncCourseSearchView(ASerializeGetParamsViewMixin, APIView):
    params_serializer_class = CourseSearchParamsSerializer

    async def get(self, request):
        params = await self.avalidated_params()
        return Response(await search_courses(**params))

Lists with additional data

ListWithAdditionalDataMixin serializes an object containing a queryset and additional fields:

def list(self, request, *args, **kwargs):
    return self.list_with_additional_data(
        request,
        additional_data={"facets": build_facets()},
        objects_field_name="courses",
    )

The asynchronous AListWithAdditionalDataMixin provides await alist_with_additional_data(...). Both variants apply filter_queryset() and keep the queryset lazy until serialization.

Pagination

LimitOffsetAllPagination

Extends DRF LimitOffsetPagination with ?all=true:

from yandex_drf_mixins.drf import LimitOffsetAllPagination


class CourseViewSet(BaseModelViewSet):
    pagination_class = LimitOffsetAllPagination
  • without all, standard limit/offset pagination is used;
  • ?all=true returns all items as one lazy queryset slice;
  • an invalid boolean value is treated as False;
  • all is added to OpenAPI operation parameters;
  • the legacy CoreAPI schema is not supported.

Asynchronous pagination

  • ALimitOffsetPagination is the asynchronous equivalent of standard limit/offset pagination;
  • ALimitOffsetAllPagination additionally supports ?all=true;
  • aget_count() uses QuerySet.acount() and falls back to len() for ordinary sequences;
  • apaginate_queryset() returns a lazy slice without converting it to list.

Base viewsets

BaseModelViewSet

Combines:

  • ActionSerializerMixin;
  • create/update with retrieve serialization;
  • update-or-create;
  • protected deletion;
  • lists with additional data;
  • the standard DRF ModelViewSet.

ABaseModelViewSet

The asynchronous base class includes:

  • AListModelMixin with alist();
  • asynchronous create/update/update-or-create/delete mixins;
  • AListWithAdditionalDataMixin;
  • aget_object() through adrf.shortcuts.aget_object_or_404;
  • acheck_object_permissions() with mixed sync/async permission support;
  • apaginate_queryset() adapters for asynchronous and regular paginators.

get_queryset() may be synchronous or declared with async def; the library detects the variant with iscoroutinefunction. filter_queryset() intentionally remains synchronous.

ADRF example:

from yandex_drf_mixins.adrf import ABaseModelViewSet, ALimitOffsetAllPagination


class StaffOccupationViewSet(ABaseModelViewSet):
    queryset = StaffOccupation.objects.select_related("direction")
    serializer_class = StaffOccupationSerializer
    pagination_class = ALimitOffsetAllPagination

    async def list(self, request, *args, **kwargs):
        return await self.alist(request, *args, **kwargs)

Every coroutine method owned by the library has an a prefix. Synchronous methods are not duplicated in ADRF classes.

Canonical courses example

The sanitized LMS courses application is available under examples/courses. It demonstrates realistic viewsets, serializers, filters, pagination, CRUD, upsert, protected deletion, and compact tests built with GenericRequestMixin. See examples/README.md for setup and test commands.

Running library tests

Run commands from the repository root. For the complete suite, including the ADRF contract, create an isolated environment and install development dependencies:

python3.14 -m venv venv
source venv/bin/activate
python3 -m pip install -e '.[dev]'
python3 -m pytest

DJANGO_SETTINGS_MODULE=tests.settings and the test directory are configured in pyproject.toml, so they do not need to be passed on the command line.

Run contract groups independently:

# Synchronous DRF components
python3 -m pytest tests/test_drf.py

# Asynchronous ADRF components
python3 -m pytest tests/test_adrf.py

# Public imports, testing mixins, and release skill
python3 -m pytest \
  tests/test_public_api.py \
  tests/test_testing.py \
  tests/test_release_skill.py

The CI and release workflows test the supported boundaries and current upstream combinations explicitly, including Python 3.15 with Django 6.1 and DRF 3.18. For local boundary checks, repeat the wheel tests on Python 3.10 and Python 3.15. If ADRF is not installed, ADRF-specific tests are skipped while DRF and testing contracts must still pass.

Development

python3 -m pip install -e '.[dev]'
python3 -m pytest
python3 -m black --check src tests
python3 -m isort --check-only src tests
python3 -m flake8 src tests
python3 -m mypy --explicit-package-bases src/yandex_drf_mixins
PYTHONPATH=.:src python3 -m pylint src/yandex_drf_mixins
python3 -m bandit -q -r src
python3 -m build

Build and test the wheel locally in LMS before publishing.

Releases

Releases use two runs of .github/workflows/release.yml. A signed v<version> tag triggers compatibility tests, quality gates, and distribution builds, but does not publish. After the tag CI and artifacts have been reviewed and the release author separately approves publication, a maintainer manually dispatches the workflow on that exact tag. The dispatch repeats the gates, builds and checks the distributions, publishes them to PyPI with OIDC Trusted Publishing, and creates a GitHub Release with the same artifacts only after PyPI succeeds.

One-time repository setup is required:

  1. Add a PyPI Trusted Publisher for owner yandex, repository drf-mixins, workflow release.yml, with the optional environment field empty. The organization's legacy GitHub Silver plan does not support Environments.
  2. Protect the v* tag namespace so only release maintainers can create tags; restrict tag updates and deletions too. If tag protection is unavailable, stop and agree on an alternative security design before releasing.
  3. Protect main with required CI and independent review of release-workflow changes. A manual workflow dispatch can be started by anyone with repository write access; it is not equivalent to a protected environment approval.

Use .agents/yandex-drf-mixins-release/skill.md to prepare a version bump, verify the release candidate, create the tag after its pull request has been merged, and request a separate approval before manually dispatching publication. Never use a long-lived PyPI token or upload distributions locally.

Metadata

Release files for yandex-drf-mixins 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for yandex-drf-mixins 0.1.3
File Size Uploaded Provenance Actions
yandex_drf_mixins-0.1.3.tar.gz 38.8 kB With provenance Details for yandex_drf_mixins-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for yandex-drf-mixins 0.1.3
File Interpreter ABI Platform Actions
yandex_drf_mixins-0.1.3-py3-none-any.whl Python 3 none any Details for yandex_drf_mixins-0.1.3-py3-none-any.whl

Total release size: 68.0 kB

Release files / yandex_drf_mixins-0.1.3.tar.gz

Download URL yandex_drf_mixins-0.1.3.tar.gz
Size 38.8 kB
Tags Source
SHA-256 checksum
How to use checksums
ff6a0ef2be5f3ad15c386c5cd26e28eb90d987ef96f512c01d47883b2a20f881
BLAKE2b-256 checksum
How to use checksums
ed3ac5841b9a299394393a4f812f98872580f4ef944aa70924f7f397ae23dc42
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / yandex_drf_mixins-0.1.3-py3-none-any.whl

Download URL yandex_drf_mixins-0.1.3-py3-none-any.whl
Size 29.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8ecbd065f77eb4b806711f96b99fd59da728f4e3de25ef5e26bcccf75744f35b
BLAKE2b-256 checksum
How to use checksums
fcec658f2ca1172c6111588486309bd214d40208ca617ddebc425dc9af9f2438
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for yandex-drf-mixins 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for yandex_drf_mixins-0.1.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page