Skip to content

Commit c68333c

Browse files
add QuerySetModelSchemaMixin for ninja.ModelSchema
1 parent de4eaf3 commit c68333c

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

pyproject.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ dev = [
3939
"coverage[toml]",
4040
"django-stubs",
4141
"django-stubs-ext",
42-
"django-twc-toolbox[cuid,history]",
42+
"django-twc-toolbox[cuid,history,ninja]",
4343
"faker",
4444
"hatch",
4545
"mypy",
@@ -63,6 +63,7 @@ docs = [
6363
]
6464
history = ["django-simple-history"]
6565
lint = ["pre-commit"]
66+
ninja = ["django-ninja"]
6667

6768
[project.urls]
6869
Documentation = "https://django-twc-toolbox.westervelt.dev/"

src/django_twc_toolbox/mixins/__init__.py

Whitespace-only changes.
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from __future__ import annotations
2+
3+
from typing import Any # pyright: ignore[reportAny]
4+
from typing import Generic
5+
from typing import TypeVar
6+
from typing import cast
7+
8+
from django.db.models import Model
9+
from django.db.models import QuerySet
10+
from ninja import ModelSchema
11+
12+
_T = TypeVar("_T", bound=ModelSchema)
13+
_M = TypeVar("_M", bound=Model)
14+
15+
16+
class QuerySetModelSchemaMixin(Generic[_T, _M]):
17+
@classmethod
18+
def from_queryset(cls: Any, queryset: QuerySet[_M]) -> list[_T]: # pyright: ignore[reportAny]
19+
schema_cls = cast(type[_T], cls)
20+
return [schema_cls.from_orm(obj) for obj in queryset.iterator()]

0 commit comments

Comments
 (0)