django-ninja-aio-crud 0.11.4__py3-none-any.whl → 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {django_ninja_aio_crud-0.11.4.dist-info → django_ninja_aio_crud-1.0.0.dist-info}/METADATA +1 -1
- {django_ninja_aio_crud-0.11.4.dist-info → django_ninja_aio_crud-1.0.0.dist-info}/RECORD +7 -7
- ninja_aio/__init__.py +1 -1
- ninja_aio/schemas.py +40 -2
- ninja_aio/views.py +185 -114
- {django_ninja_aio_crud-0.11.4.dist-info → django_ninja_aio_crud-1.0.0.dist-info}/WHEEL +0 -0
- {django_ninja_aio_crud-0.11.4.dist-info → django_ninja_aio_crud-1.0.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
ninja_aio/__init__.py,sha256=
|
|
1
|
+
ninja_aio/__init__.py,sha256=0C1TJ30_2xcqtKhHchk1gb1IzGrxY2u1ufIO-lIRgRM,119
|
|
2
2
|
ninja_aio/api.py,sha256=Fe6l3YCy7MW5TY4-Lbl80CFuK2NT2Y7tHfmqPk6Mqak,1735
|
|
3
3
|
ninja_aio/auth.py,sha256=zUwruKcz7MXuOnWp5k1CCSwEc8s2Lyqqk7Qm9kPbJ3o,5149
|
|
4
4
|
ninja_aio/decorators.py,sha256=LsvHbMxmw_So8NV0ey5NRRvSbfYkOZLeLQ4Fix7rQAY,5519
|
|
@@ -6,10 +6,10 @@ ninja_aio/exceptions.py,sha256=iEX4PNqtRXXr75M8veOynmFZcIE5lGURHU_ISSgzX0Y,2578
|
|
|
6
6
|
ninja_aio/models.py,sha256=-p1wgOg-r5bYWQ9DzUSNKxsUvWiDg6kruMQ_LxZFvQE,32948
|
|
7
7
|
ninja_aio/parsers.py,sha256=e_4lGCPV7zs-HTqtdJTc8yQD2KPAn9njbL8nF_Mmgkc,153
|
|
8
8
|
ninja_aio/renders.py,sha256=0eYklRKd59aV4cZDom5vLZyA99Ob17OwkpMybsRXvyg,1970
|
|
9
|
-
ninja_aio/schemas.py,sha256=
|
|
9
|
+
ninja_aio/schemas.py,sha256=iv3VHCMlzez6Qs70zITYIwEz0EFOOaMPDVGRcTZCygA,1875
|
|
10
10
|
ninja_aio/types.py,sha256=TJSGlA7bt4g9fvPhJ7gzH5tKbLagPmZUzfgttEOp4xs,468
|
|
11
|
-
ninja_aio/views.py,sha256=
|
|
12
|
-
django_ninja_aio_crud-0.
|
|
13
|
-
django_ninja_aio_crud-0.
|
|
14
|
-
django_ninja_aio_crud-0.
|
|
15
|
-
django_ninja_aio_crud-0.
|
|
11
|
+
ninja_aio/views.py,sha256=7sv8tpRp8CJC2sxQr-jmbjyjcJe7DabYPf8F7nieZ4Y,23518
|
|
12
|
+
django_ninja_aio_crud-1.0.0.dist-info/licenses/LICENSE,sha256=yrDAYcm0gRp_Qyzo3GQa4BjYjWRkAhGC8QRva__RYq0,1073
|
|
13
|
+
django_ninja_aio_crud-1.0.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
|
|
14
|
+
django_ninja_aio_crud-1.0.0.dist-info/METADATA,sha256=aV0vq6ijySGbggzrwNJ1mCC7HG_6fo1jeF9Ybb_j9Mk,14216
|
|
15
|
+
django_ninja_aio_crud-1.0.0.dist-info/RECORD,,
|
ninja_aio/__init__.py
CHANGED
ninja_aio/schemas.py
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
from typing import Optional, Type
|
|
2
|
+
|
|
1
3
|
from ninja import Schema
|
|
2
|
-
from
|
|
4
|
+
from .models import ModelSerializer
|
|
5
|
+
from django.db.models import Model
|
|
6
|
+
from pydantic import BaseModel, RootModel, ConfigDict
|
|
3
7
|
|
|
4
8
|
|
|
5
9
|
class GenericMessageSchema(RootModel[dict[str, str]]):
|
|
@@ -26,4 +30,38 @@ class M2MRemoveSchemaIn(Schema):
|
|
|
26
30
|
|
|
27
31
|
class M2MSchemaIn(Schema):
|
|
28
32
|
add: list = []
|
|
29
|
-
remove: list = []
|
|
33
|
+
remove: list = []
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class M2MRelationSchema(BaseModel):
|
|
37
|
+
"""
|
|
38
|
+
Configuration schema for declaring a Many-to-Many relation in the API.
|
|
39
|
+
|
|
40
|
+
Attributes:
|
|
41
|
+
model (Type[ModelSerializer] | Type[Model]): Target model class or its serializer.
|
|
42
|
+
related_name (str): Name of the relationship field on the Django model.
|
|
43
|
+
add (bool): Enable adding related objects (default True).
|
|
44
|
+
remove (bool): Enable removing related objects (default True).
|
|
45
|
+
get (bool): Enable retrieving related objects (default True).
|
|
46
|
+
path (str | None): Optional custom URL path segment (None/"" => auto-generated).
|
|
47
|
+
auth (list | None): Optional list of authentication backends for the endpoints.
|
|
48
|
+
filters (dict[str, tuple] | None): Field name -> (type, default) pairs for query filtering.
|
|
49
|
+
|
|
50
|
+
Example:
|
|
51
|
+
M2MRelationSchema(
|
|
52
|
+
model=BookSerializer,
|
|
53
|
+
related_name="authors",
|
|
54
|
+
filters={"country": ("str", '')}
|
|
55
|
+
)
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
model: Type[ModelSerializer] | Type[Model]
|
|
59
|
+
related_name: str
|
|
60
|
+
add: bool = True
|
|
61
|
+
remove: bool = True
|
|
62
|
+
get: bool = True
|
|
63
|
+
path: Optional[str] = ""
|
|
64
|
+
auth: Optional[list] = None
|
|
65
|
+
filters: Optional[dict[str, tuple]] = None
|
|
66
|
+
|
|
67
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
ninja_aio/views.py
CHANGED
|
@@ -15,6 +15,7 @@ from .schemas import (
|
|
|
15
15
|
M2MSchemaIn,
|
|
16
16
|
M2MAddSchemaIn,
|
|
17
17
|
M2MRemoveSchemaIn,
|
|
18
|
+
M2MRelationSchema,
|
|
18
19
|
)
|
|
19
20
|
from .types import ModelSerializerMeta, VIEW_TYPES
|
|
20
21
|
from .decorators import unique_view
|
|
@@ -75,64 +76,86 @@ class APIView:
|
|
|
75
76
|
|
|
76
77
|
class APIViewSet:
|
|
77
78
|
"""
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
This class provides methods for creating, listing, retrieving, updating,
|
|
81
|
-
and deleting objects of a specified model. It supports pagination,
|
|
82
|
-
authentication, and custom query parameters.
|
|
83
|
-
|
|
84
|
-
## Attributes:
|
|
85
|
-
- **model** (`ModelSerializer | Model`): The model for CRUD operations.
|
|
86
|
-
- **api** (`NinjaAPI`): The API instance to which the views are added.
|
|
87
|
-
- **schema_in** (`Schema | None`): Schema for input data in create/update operations.
|
|
88
|
-
- **schema_out** (`Schema | None`): Schema for output data in list/retrieve operations.
|
|
89
|
-
- **schema_update** (`Schema | None`): Schema for update operations.
|
|
90
|
-
- **auth** (`list | None`): Authentication classes for the views.
|
|
91
|
-
- **get_auth** (`list | None`): Authentication for GET requests.
|
|
92
|
-
- **post_auth** (`list | None`): Authentication for POST requests.
|
|
93
|
-
- **patch_auth** (`list | None`): Authentication for PATCH requests.
|
|
94
|
-
- **delete_auth** (`list | None`): Authentication for DELETE requests.
|
|
95
|
-
- **pagination_class** (`type[AsyncPaginationBase]`): Pagination class to use.
|
|
96
|
-
- **query_params** (`dict[str, tuple[type, ...]]`): Query parameters for filtering.
|
|
97
|
-
- **disable** (`list[type[VIEW_TYPES]]`): List of view types to disable.
|
|
98
|
-
- **api_route_path** (`str`): Base path for the API route.
|
|
99
|
-
- **list_docs** (`str`): Documentation for the list view.
|
|
100
|
-
- **create_docs** (`str`): Documentation for the create view.
|
|
101
|
-
- **retrieve_docs** (`str`): Documentation for the retrieve view.
|
|
102
|
-
- **update_docs** (`str`): Documentation for the update view.
|
|
103
|
-
- **delete_docs** (`str`): Documentation for the delete view.
|
|
104
|
-
- **m2m_relations** (`list[tuple[ModelSerializer | Model, str, str, list]]`): Many-to-many relations to manage. Each tuple contains:
|
|
105
|
-
- The related model.
|
|
106
|
-
- The related name on the main model.
|
|
107
|
-
- The name of the path, if not provided a default will be used.
|
|
108
|
-
- The authentication for the m2m views.
|
|
109
|
-
- **m2m_add** (`bool`): Enable add operation for M2M relations.
|
|
110
|
-
- **m2m_remove** (`bool`): Enable remove operation for M2M relations.
|
|
111
|
-
- **m2m_get** (`bool`): Enable get operation for M2M relations.
|
|
112
|
-
- **m2m_auth** (`list | None`): Authentication for M2M views.
|
|
113
|
-
|
|
114
|
-
## Notes:
|
|
115
|
-
If the model is a ModelSerializer instance, schemas are generated
|
|
116
|
-
automatically based on Create, Read, and Update serializers.
|
|
117
|
-
Override the `views` method to add custom views.
|
|
118
|
-
Override the `query_params_handler` method to handle query params
|
|
119
|
-
and return a filtered queryset.
|
|
120
|
-
|
|
121
|
-
## Methods:
|
|
122
|
-
- **create_view**: Creates a new object.
|
|
123
|
-
- **list_view**: Lists all objects.
|
|
124
|
-
- **retrieve_view**: Retrieves an object by its primary key.
|
|
125
|
-
- **update_view**: Updates an object by its primary key.
|
|
126
|
-
- **delete_view**: Deletes an object by its primary key.
|
|
127
|
-
- **views**: Override to add custom views.
|
|
128
|
-
- **add_views_to_route**: Adds the views to the API route.
|
|
129
|
-
|
|
130
|
-
## Example:
|
|
131
|
-
class MyModelViewSet(APIViewSet):
|
|
132
|
-
model = MyModel # Your Django model
|
|
133
|
-
api = my_api_instance # Your NinjaAPI instance
|
|
79
|
+
Base viewset generating async CRUD + optional M2M endpoints for a Django model.
|
|
134
80
|
|
|
81
|
+
Usage:
|
|
82
|
+
class MyModelViewSet(APIViewSet):
|
|
83
|
+
model = MyModel
|
|
84
|
+
api = api
|
|
135
85
|
MyModelViewSet().add_views_to_route()
|
|
86
|
+
|
|
87
|
+
Automatic schema generation:
|
|
88
|
+
If model is a ModelSerializer (subclass of ModelSerializerMeta),
|
|
89
|
+
read/create/update schemas are auto-generated from its serializers.
|
|
90
|
+
Otherwise provide schema_in / schema_out / schema_update manually.
|
|
91
|
+
|
|
92
|
+
Generated endpoints (unless disabled via `disable`):
|
|
93
|
+
POST / -> create_view (201, schema_out)
|
|
94
|
+
GET / -> list_view (200, List[schema_out] paginated)
|
|
95
|
+
GET /{pk} -> retrieve_view (200, schema_out)
|
|
96
|
+
PATCH /{pk}/ -> update_view (200, schema_out)
|
|
97
|
+
DELETE /{pk}/ -> delete_view (204)
|
|
98
|
+
|
|
99
|
+
M2M endpoints (per entry in m2m_relations) if enabled:
|
|
100
|
+
GET /{pk}/{related_path} -> list related objects (paginated)
|
|
101
|
+
POST /{pk}/{related_path}/ -> add/remove related objects (depending on m2m_add / m2m_remove)
|
|
102
|
+
|
|
103
|
+
M2M filters:
|
|
104
|
+
Each M2MRelationSchema may define a filters dict:
|
|
105
|
+
filters = { "field_name": (type, default) }
|
|
106
|
+
A dynamic Pydantic Filters schema is generated and exposed as query params
|
|
107
|
+
on the related GET endpoint: /{pk}/{related_path}?field_name=value.
|
|
108
|
+
To apply custom filter logic implement an async hook named:
|
|
109
|
+
<related_name>_query_params_handler(self, queryset, filters_dict)
|
|
110
|
+
It receives the initial related queryset and the validated/dumped filters
|
|
111
|
+
dict, and must return the (optionally) filtered queryset.
|
|
112
|
+
|
|
113
|
+
Example:
|
|
114
|
+
class UserViewSet(APIViewSet):
|
|
115
|
+
model = models.User
|
|
116
|
+
m2m_relations = [
|
|
117
|
+
M2MRelationSchema(
|
|
118
|
+
model=models.Tag,
|
|
119
|
+
related_name="tags",
|
|
120
|
+
filters={
|
|
121
|
+
"name": (str, "")
|
|
122
|
+
}
|
|
123
|
+
)
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
async def tags_query_params_handler(self, queryset, filters):
|
|
127
|
+
name_filter = filters.get("name")
|
|
128
|
+
if name_filter:
|
|
129
|
+
queryset = queryset.filter(name__icontains=name_filter)
|
|
130
|
+
return queryset
|
|
131
|
+
|
|
132
|
+
If filters is empty or omitted no query params are added for that relation.
|
|
133
|
+
|
|
134
|
+
Attribute summary:
|
|
135
|
+
model: Django model or ModelSerializer.
|
|
136
|
+
api: NinjaAPI instance.
|
|
137
|
+
schema_in / schema_out / schema_update: Pydantic schemas (auto when ModelSerializer).
|
|
138
|
+
auth: Default auth list or NOT_SET (no auth). Verb specific auth: get_auth, post_auth, patch_auth, delete_auth.
|
|
139
|
+
pagination_class: AsyncPaginationBase subclass (default PageNumberPagination).
|
|
140
|
+
query_params: Dict[str, (type, default)] to build a dynamic filters schema for list_view.
|
|
141
|
+
disable: List of view type strings: 'create','list','retrieve','update','delete','all'.
|
|
142
|
+
api_route_path: Base path; auto-resolved from verbose name if empty.
|
|
143
|
+
list_docs / create_docs / retrieve_docs / update_docs / delete_docs: Endpoint descriptions.
|
|
144
|
+
m2m_relations: List of M2MRelationSchema describing related model, related_name, custom path, auth, filters.
|
|
145
|
+
m2m_add / m2m_remove / m2m_get: Enable add/remove/get M2M operations.
|
|
146
|
+
m2m_auth: Auth list for all M2M endpoints unless overridden per relation.
|
|
147
|
+
|
|
148
|
+
Overridable hooks:
|
|
149
|
+
views(): Register extra custom endpoints on self.router.
|
|
150
|
+
query_params_handler(queryset, filters): Async hook to apply list filters.
|
|
151
|
+
<related_name>_query_params_handler(queryset, filters): Async hook for per-M2M filtering.
|
|
152
|
+
|
|
153
|
+
Error responses:
|
|
154
|
+
All endpoints may return GenericMessageSchema for codes in ERROR_CODES (400,401,404,428).
|
|
155
|
+
|
|
156
|
+
Internal:
|
|
157
|
+
Dynamic path/filter schemas built with pydantic.create_model.
|
|
158
|
+
unique_view decorator prevents duplicate registration.
|
|
136
159
|
"""
|
|
137
160
|
|
|
138
161
|
model: ModelSerializer | Model
|
|
@@ -154,10 +177,7 @@ class APIViewSet:
|
|
|
154
177
|
retrieve_docs = "Retrieve a specific object by its primary key."
|
|
155
178
|
update_docs = "Update an object by its primary key."
|
|
156
179
|
delete_docs = "Delete an object by its primary key."
|
|
157
|
-
m2m_relations: list[
|
|
158
|
-
m2m_add = True
|
|
159
|
-
m2m_remove = True
|
|
160
|
-
m2m_get = True
|
|
180
|
+
m2m_relations: list[M2MRelationSchema] = []
|
|
161
181
|
m2m_auth: list | None = NOT_SET
|
|
162
182
|
|
|
163
183
|
def __init__(self) -> None:
|
|
@@ -166,6 +186,7 @@ class APIViewSet:
|
|
|
166
186
|
self.schema_out, self.schema_in, self.schema_update = self.get_schemas()
|
|
167
187
|
self.path_schema = self._generate_path_schema()
|
|
168
188
|
self.filters_schema = self._generate_filters_schema()
|
|
189
|
+
self.m2m_filters_schemas = self._generate_m2m_filters_schemas()
|
|
169
190
|
self.model_verbose_name = self.model._meta.verbose_name.capitalize()
|
|
170
191
|
self.router_tag = self.model_verbose_name
|
|
171
192
|
self.router = Router(tags=[self.router_tag])
|
|
@@ -180,8 +201,7 @@ class APIViewSet:
|
|
|
180
201
|
@property
|
|
181
202
|
def _crud_views(self):
|
|
182
203
|
"""
|
|
183
|
-
|
|
184
|
-
value: tuple with schema and view method
|
|
204
|
+
Mapping of CRUD operation name to (response schema, view factory).
|
|
185
205
|
"""
|
|
186
206
|
return {
|
|
187
207
|
"create": (self.schema_in, self.create_view),
|
|
@@ -192,6 +212,9 @@ class APIViewSet:
|
|
|
192
212
|
}
|
|
193
213
|
|
|
194
214
|
def _auth_view(self, view_type: str):
|
|
215
|
+
"""
|
|
216
|
+
Resolve auth for a specific HTTP verb; falls back to self.auth if NOT_SET.
|
|
217
|
+
"""
|
|
195
218
|
auth = getattr(self, f"{view_type}_auth", None)
|
|
196
219
|
return auth if auth is not NOT_SET else self.auth
|
|
197
220
|
|
|
@@ -208,20 +231,47 @@ class APIViewSet:
|
|
|
208
231
|
return self._auth_view("delete")
|
|
209
232
|
|
|
210
233
|
def _generate_schema(self, fields: dict, name: str) -> Schema:
|
|
234
|
+
"""
|
|
235
|
+
Dynamically build a Pydantic model for path / filter schemas.
|
|
236
|
+
"""
|
|
211
237
|
return create_model(f"{self.model_util.model_name}{name}", **fields)
|
|
212
238
|
|
|
213
239
|
def _generate_path_schema(self):
|
|
240
|
+
"""
|
|
241
|
+
Schema containing only the primary key field for path resolution.
|
|
242
|
+
"""
|
|
214
243
|
return self._generate_schema(
|
|
215
244
|
{self.model_util.model_pk_name: (int | str, ...)}, "PathSchema"
|
|
216
245
|
)
|
|
217
246
|
|
|
218
247
|
def _generate_filters_schema(self):
|
|
248
|
+
"""
|
|
249
|
+
Build filters schema from query_params definition.
|
|
250
|
+
"""
|
|
219
251
|
return self._generate_schema(self.query_params, "FiltersSchema")
|
|
220
252
|
|
|
253
|
+
def _generate_m2m_filters_schemas(self):
|
|
254
|
+
"""
|
|
255
|
+
Build per-relation filters schemas for M2M endpoints.
|
|
256
|
+
"""
|
|
257
|
+
return {
|
|
258
|
+
m2m_data.related_name: self._generate_schema(
|
|
259
|
+
{} if not m2m_data.filters else m2m_data.filters,
|
|
260
|
+
f"{self.model_util.model_name}{m2m_data.related_name.capitalize()}FiltersSchema",
|
|
261
|
+
)
|
|
262
|
+
for m2m_data in self.m2m_relations
|
|
263
|
+
}
|
|
264
|
+
|
|
221
265
|
def _get_pk(self, data: Schema):
|
|
266
|
+
"""
|
|
267
|
+
Extract pk from a path schema instance.
|
|
268
|
+
"""
|
|
222
269
|
return data.model_dump()[self.model_util.model_pk_name]
|
|
223
270
|
|
|
224
271
|
def get_schemas(self):
|
|
272
|
+
"""
|
|
273
|
+
Return (schema_out, schema_in, schema_update), generating them if model is a ModelSerializer.
|
|
274
|
+
"""
|
|
225
275
|
if isinstance(self.model, ModelSerializerMeta):
|
|
226
276
|
return (
|
|
227
277
|
self.model.generate_read_s(),
|
|
@@ -234,13 +284,16 @@ class APIViewSet:
|
|
|
234
284
|
self, queryset: QuerySet[ModelSerializer], filters: dict
|
|
235
285
|
):
|
|
236
286
|
"""
|
|
237
|
-
Override
|
|
238
|
-
|
|
239
|
-
|
|
287
|
+
Override to apply custom filtering logic for list_view.
|
|
288
|
+
filters is already validated and dumped.
|
|
289
|
+
Return the (possibly modified) queryset.
|
|
240
290
|
"""
|
|
241
291
|
return queryset
|
|
242
292
|
|
|
243
293
|
def create_view(self):
|
|
294
|
+
"""
|
|
295
|
+
Register create endpoint.
|
|
296
|
+
"""
|
|
244
297
|
@self.router.post(
|
|
245
298
|
self.path,
|
|
246
299
|
auth=self.post_view_auth(),
|
|
@@ -255,6 +308,9 @@ class APIViewSet:
|
|
|
255
308
|
return create
|
|
256
309
|
|
|
257
310
|
def list_view(self):
|
|
311
|
+
"""
|
|
312
|
+
Register list endpoint with pagination and optional filters.
|
|
313
|
+
"""
|
|
258
314
|
@self.router.get(
|
|
259
315
|
self.get_path,
|
|
260
316
|
auth=self.get_view_auth(),
|
|
@@ -288,6 +344,9 @@ class APIViewSet:
|
|
|
288
344
|
return list
|
|
289
345
|
|
|
290
346
|
def retrieve_view(self):
|
|
347
|
+
"""
|
|
348
|
+
Register retrieve endpoint.
|
|
349
|
+
"""
|
|
291
350
|
@self.router.get(
|
|
292
351
|
self.get_path_retrieve,
|
|
293
352
|
auth=self.get_view_auth(),
|
|
@@ -303,6 +362,9 @@ class APIViewSet:
|
|
|
303
362
|
return retrieve
|
|
304
363
|
|
|
305
364
|
def update_view(self):
|
|
365
|
+
"""
|
|
366
|
+
Register update endpoint.
|
|
367
|
+
"""
|
|
306
368
|
@self.router.patch(
|
|
307
369
|
self.path_retrieve,
|
|
308
370
|
auth=self.patch_view_auth(),
|
|
@@ -323,6 +385,9 @@ class APIViewSet:
|
|
|
323
385
|
return update
|
|
324
386
|
|
|
325
387
|
def delete_view(self):
|
|
388
|
+
"""
|
|
389
|
+
Register delete endpoint.
|
|
390
|
+
"""
|
|
326
391
|
@self.router.delete(
|
|
327
392
|
self.path_retrieve,
|
|
328
393
|
auth=self.delete_view_auth(),
|
|
@@ -338,35 +403,8 @@ class APIViewSet:
|
|
|
338
403
|
|
|
339
404
|
def views(self):
|
|
340
405
|
"""
|
|
341
|
-
Override
|
|
342
|
-
|
|
343
|
-
async def some_method(request, *args, **kwargs):
|
|
344
|
-
pass
|
|
345
|
-
|
|
346
|
-
You can add multilple views just doing:
|
|
347
|
-
|
|
348
|
-
@self.router.get(some_path, response=some_schema)
|
|
349
|
-
async def some_method(request, *args, **kwargs):
|
|
350
|
-
pass
|
|
351
|
-
|
|
352
|
-
@self.router.post(some_path, response=some_schema)
|
|
353
|
-
async def some_method(request, *args, **kwargs):
|
|
354
|
-
pass
|
|
355
|
-
|
|
356
|
-
If you provided a list of auths you can chose which of your views
|
|
357
|
-
should be authenticated:
|
|
358
|
-
|
|
359
|
-
AUTHENTICATED VIEW:
|
|
360
|
-
|
|
361
|
-
@self.router.get(some_path, response=some_schema, auth=self.auth)
|
|
362
|
-
async def some_method(request, *args, **kwargs):
|
|
363
|
-
pass
|
|
364
|
-
|
|
365
|
-
NOT AUTHENTICATED VIEW:
|
|
366
|
-
|
|
367
|
-
@self.router.post(some_path, response=some_schema)
|
|
368
|
-
async def some_method(request, *args, **kwargs):
|
|
369
|
-
pass
|
|
406
|
+
Override to register custom non-CRUD endpoints on self.router.
|
|
407
|
+
Use auth=self.auth or verb specific auth attributes if needed.
|
|
370
408
|
"""
|
|
371
409
|
|
|
372
410
|
async def _check_m2m_objs(
|
|
@@ -377,6 +415,10 @@ class APIViewSet:
|
|
|
377
415
|
related_manager: QuerySet,
|
|
378
416
|
remove: bool = False,
|
|
379
417
|
):
|
|
418
|
+
"""
|
|
419
|
+
Validate requested add/remove pk list for M2M operations.
|
|
420
|
+
Returns (errors, details, objects_to_process).
|
|
421
|
+
"""
|
|
380
422
|
errors, objs_detail, objs = [], [], []
|
|
381
423
|
rel_objs = [rel_obj async for rel_obj in related_manager.select_related().all()]
|
|
382
424
|
rel_model_name = model._meta.verbose_name.capitalize()
|
|
@@ -389,7 +431,7 @@ class APIViewSet:
|
|
|
389
431
|
continue
|
|
390
432
|
if remove ^ (rel_obj in rel_objs):
|
|
391
433
|
errors.append(
|
|
392
|
-
f"{rel_model_name} with id {obj_pk} is {'not ' if remove else ''}
|
|
434
|
+
f"{rel_model_name} with id {obj_pk} is {'not ' if remove else ''}in {self.model_util.model_name}"
|
|
393
435
|
)
|
|
394
436
|
continue
|
|
395
437
|
objs.append(rel_obj)
|
|
@@ -399,22 +441,26 @@ class APIViewSet:
|
|
|
399
441
|
return errors, objs_detail, objs
|
|
400
442
|
|
|
401
443
|
def _m2m_views(self):
|
|
444
|
+
"""
|
|
445
|
+
Register M2M get/manage endpoints for each relation in m2m_relations.
|
|
446
|
+
Supports optional per-relation filters and custom query handler:
|
|
447
|
+
<related_name>_query_params_handler.
|
|
448
|
+
"""
|
|
402
449
|
for m2m_data in self.m2m_relations:
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
elif len(m2m_data) == 4:
|
|
407
|
-
model, related_name, m2m_path, m2m_auth = m2m_data
|
|
408
|
-
else:
|
|
409
|
-
model, related_name = m2m_data
|
|
410
|
-
m2m_path = ""
|
|
450
|
+
model = m2m_data.model
|
|
451
|
+
related_name = m2m_data.related_name
|
|
452
|
+
m2m_auth = m2m_data.auth or self.m2m_auth
|
|
411
453
|
rel_util = ModelUtil(model)
|
|
412
454
|
rel_path = (
|
|
413
455
|
rel_util.verbose_name_path_resolver()
|
|
414
|
-
if not
|
|
415
|
-
else
|
|
456
|
+
if not m2m_data.path
|
|
457
|
+
else m2m_data.path
|
|
416
458
|
)
|
|
417
|
-
|
|
459
|
+
m2m_add = m2m_data.add
|
|
460
|
+
m2m_remove = m2m_data.remove
|
|
461
|
+
m2m_get = m2m_data.get
|
|
462
|
+
filters_schema = self.m2m_filters_schemas.get(related_name)
|
|
463
|
+
if m2m_get:
|
|
418
464
|
|
|
419
465
|
@self.router.get(
|
|
420
466
|
f"{self.path_retrieve}{rel_path}",
|
|
@@ -428,10 +474,28 @@ class APIViewSet:
|
|
|
428
474
|
)
|
|
429
475
|
@unique_view(f"get_{self.model_util.model_name}_{rel_path}")
|
|
430
476
|
@paginate(self.pagination_class)
|
|
431
|
-
async def get_related(
|
|
477
|
+
async def get_related(
|
|
478
|
+
request: HttpRequest,
|
|
479
|
+
pk: Path[self.path_schema], # type: ignore
|
|
480
|
+
filters: Query[filters_schema] = None # type: ignore
|
|
481
|
+
):
|
|
432
482
|
obj = await self.model_util.get_object(request, self._get_pk(pk))
|
|
433
483
|
related_manager = getattr(obj, related_name)
|
|
434
484
|
related_qs = related_manager.all()
|
|
485
|
+
if (
|
|
486
|
+
filters is not None
|
|
487
|
+
and (
|
|
488
|
+
query_handler := getattr(
|
|
489
|
+
self,
|
|
490
|
+
f"{m2m_data.related_name}_query_params_handler",
|
|
491
|
+
None,
|
|
492
|
+
)
|
|
493
|
+
)
|
|
494
|
+
is not None
|
|
495
|
+
):
|
|
496
|
+
related_qs = await query_handler(
|
|
497
|
+
related_qs, filters.model_dump()
|
|
498
|
+
)
|
|
435
499
|
related_objs = [
|
|
436
500
|
await rel_util.read_s(
|
|
437
501
|
request, rel_obj, model.generate_related_s()
|
|
@@ -440,14 +504,14 @@ class APIViewSet:
|
|
|
440
504
|
]
|
|
441
505
|
return related_objs
|
|
442
506
|
|
|
443
|
-
if
|
|
444
|
-
summary = f"{'Add or Remove' if
|
|
445
|
-
description = f"{'Add or remove' if
|
|
507
|
+
if m2m_add or m2m_remove:
|
|
508
|
+
summary = f"{'Add or Remove' if m2m_add and m2m_remove else 'Add' if m2m_add else 'Remove'} {rel_util.model._meta.verbose_name_plural.capitalize()}"
|
|
509
|
+
description = f"{'Add or remove' if m2m_add and m2m_remove else 'Add' if m2m_add else 'Remove'} {rel_util.model._meta.verbose_name_plural.capitalize()}"
|
|
446
510
|
schema_in = (
|
|
447
511
|
M2MSchemaIn
|
|
448
|
-
if
|
|
512
|
+
if m2m_add and m2m_remove
|
|
449
513
|
else M2MAddSchemaIn
|
|
450
|
-
if
|
|
514
|
+
if m2m_add
|
|
451
515
|
else M2MRemoveSchemaIn
|
|
452
516
|
)
|
|
453
517
|
|
|
@@ -472,7 +536,7 @@ class APIViewSet:
|
|
|
472
536
|
add_errors, add_details, add_objs = [], [], []
|
|
473
537
|
remove_errors, remove_details, remove_objs = [], [], []
|
|
474
538
|
|
|
475
|
-
if
|
|
539
|
+
if m2m_add and hasattr(data, "add"):
|
|
476
540
|
(
|
|
477
541
|
add_errors,
|
|
478
542
|
add_details,
|
|
@@ -480,7 +544,7 @@ class APIViewSet:
|
|
|
480
544
|
) = await self._check_m2m_objs(
|
|
481
545
|
request, data.add, model, related_manager
|
|
482
546
|
)
|
|
483
|
-
if
|
|
547
|
+
if m2m_remove and hasattr(data, "remove"):
|
|
484
548
|
(
|
|
485
549
|
remove_errors,
|
|
486
550
|
remove_details,
|
|
@@ -512,6 +576,10 @@ class APIViewSet:
|
|
|
512
576
|
}
|
|
513
577
|
|
|
514
578
|
def _add_views(self):
|
|
579
|
+
"""
|
|
580
|
+
Register CRUD (unless disabled), custom views, and M2M endpoints.
|
|
581
|
+
If 'all' in disable only CRUD is skipped; M2M + custom still added.
|
|
582
|
+
"""
|
|
515
583
|
if "all" in self.disable:
|
|
516
584
|
if self.m2m_relations:
|
|
517
585
|
self._m2m_views()
|
|
@@ -530,4 +598,7 @@ class APIViewSet:
|
|
|
530
598
|
return self.router
|
|
531
599
|
|
|
532
600
|
def add_views_to_route(self):
|
|
601
|
+
"""
|
|
602
|
+
Attach router with registered endpoints to the NinjaAPI instance.
|
|
603
|
+
"""
|
|
533
604
|
return self.api.add_router(f"{self.api_route_path}", self._add_views())
|
|
File without changes
|
{django_ninja_aio_crud-0.11.4.dist-info → django_ninja_aio_crud-1.0.0.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|