From c68333c70959bdb8a052169c811f9a2a96e682aa Mon Sep 17 00:00:00 2001 From: Josh Date: Thu, 11 Jul 2024 09:44:21 -0500 Subject: [PATCH] add `QuerySetModelSchemaMixin` for `ninja.ModelSchema` --- pyproject.toml | 3 ++- src/django_twc_toolbox/mixins/__init__.py | 0 src/django_twc_toolbox/mixins/ninja.py | 20 ++++++++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 src/django_twc_toolbox/mixins/__init__.py create mode 100644 src/django_twc_toolbox/mixins/ninja.py diff --git a/pyproject.toml b/pyproject.toml index 4b3ca5b..7b1e69a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,7 +39,7 @@ dev = [ "coverage[toml]", "django-stubs", "django-stubs-ext", - "django-twc-toolbox[cuid,history]", + "django-twc-toolbox[cuid,history,ninja]", "faker", "hatch", "mypy", @@ -63,6 +63,7 @@ docs = [ ] history = ["django-simple-history"] lint = ["pre-commit"] +ninja = ["django-ninja"] [project.urls] Documentation = "https://django-twc-toolbox.westervelt.dev/" diff --git a/src/django_twc_toolbox/mixins/__init__.py b/src/django_twc_toolbox/mixins/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/django_twc_toolbox/mixins/ninja.py b/src/django_twc_toolbox/mixins/ninja.py new file mode 100644 index 0000000..1c8528b --- /dev/null +++ b/src/django_twc_toolbox/mixins/ninja.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from typing import Any # pyright: ignore[reportAny] +from typing import Generic +from typing import TypeVar +from typing import cast + +from django.db.models import Model +from django.db.models import QuerySet +from ninja import ModelSchema + +_T = TypeVar("_T", bound=ModelSchema) +_M = TypeVar("_M", bound=Model) + + +class QuerySetModelSchemaMixin(Generic[_T, _M]): + @classmethod + def from_queryset(cls: Any, queryset: QuerySet[_M]) -> list[_T]: # pyright: ignore[reportAny] + schema_cls = cast(type[_T], cls) + return [schema_cls.from_orm(obj) for obj in queryset.iterator()]