| 1 |
from typing import Any, List, Optional, Union, no_type_check |
| 2 |
|
| 3 |
from django.apps import apps |
| 4 |
from django.db.models import Model as DjangoModel |
| 5 |
from pydantic.dataclasses import dataclass |
| 6 |
|
| 7 |
from ninja.compatibility.util import get_annotations_from_namespace |
| 8 |
from ninja.errors import ConfigError |
| 9 |
from ninja.orm.factory import create_schema |
| 10 |
from ninja.schema import ResolverMetaclass, Schema |
| 11 |
|
| 12 |
_is_modelschema_class_defined = False |
| 13 |
|
| 14 |
|
| 15 |
@dataclass |
| 16 |
class MetaConf: |
| 17 |
model: Any |
| 18 |
fields: Optional[List[str]] = None |
| 19 |
exclude: Union[List[str], str, None] = None |
| 20 |
fields_optional: Union[List[str], str, None] = None |
| 21 |
|
| 22 |
@staticmethod |
| 23 |
def from_schema_class(name: str, namespace: dict) -> "MetaConf": |
| 24 |
if "Config" in namespace: |
| 25 |
raise ConfigError( |
| 26 |
"The use of `Config` class is removed for ModelSchema, use 'Meta' instead", |
| 27 |
) |
| 28 |
if "Meta" in namespace: |
| 29 |
meta = namespace["Meta"] |
| 30 |
model = meta.model |
| 31 |
if isinstance(model, str): |
| 32 |
try: |
| 33 |
app_label, model_name = model.split(".") |
| 34 |
except ValueError as e: |
| 35 |
raise ValueError( |
| 36 |
f"Model string must be in format 'app_label.ModelName', got: {model}" |
| 37 |
) from e |
| 38 |
model = apps.get_model(app_label, model_name) |
| 39 |
fields = getattr(meta, "fields", None) |
| 40 |
exclude = getattr(meta, "exclude", None) |
| 41 |
optional_fields = getattr(meta, "fields_optional", None) |
| 42 |
|
| 43 |
else: |
| 44 |
raise ConfigError(f"ModelSchema class '{name}' requires a 'Meta' subclass") |
| 45 |
|
| 46 |
assert issubclass(model, DjangoModel) |
| 47 |
|
| 48 |
if not fields and not exclude: |
| 49 |
raise ConfigError( |
| 50 |
"Creating a ModelSchema without either the 'fields' attribute" |
| 51 |
" or the 'exclude' attribute is prohibited" |
| 52 |
) |
| 53 |
|
| 54 |
if fields == "__all__": |
| 55 |
fields = None |
| 56 |
|
| 57 |
|
| 58 |
return MetaConf( |
| 59 |
model=model, |
| 60 |
fields=fields, |
| 61 |
exclude=exclude, |
| 62 |
fields_optional=optional_fields, |
| 63 |
) |
| 64 |
|
| 65 |
|
| 66 |
class ModelSchemaMetaclass(ResolverMetaclass): |
| 67 |
@no_type_check |
| 68 |
def __new__( |
| 69 |
mcs, |
| 70 |
name: str, |
| 71 |
bases: tuple, |
| 72 |
namespace: dict, |
| 73 |
**kwargs, |
| 74 |
): |
| 75 |
cls = super().__new__( |
| 76 |
mcs, |
| 77 |
name, |
| 78 |
bases, |
| 79 |
namespace, |
| 80 |
**kwargs, |
| 81 |
) |
| 82 |
for base in reversed(bases): |
| 83 |
if ( |
| 84 |
_is_modelschema_class_defined |
| 85 |
and issubclass(base, ModelSchema) |
| 86 |
and base == ModelSchema |
| 87 |
): |
| 88 |
meta_conf = MetaConf.from_schema_class(name, namespace) |
| 89 |
|
| 90 |
custom_fields = [] |
| 91 |
annotations = get_annotations_from_namespace(namespace) |
| 92 |
for attr_name, type in annotations.items(): |
| 93 |
if attr_name.startswith("_"): |
| 94 |
continue |
| 95 |
default = namespace.get(attr_name, ...) |
| 96 |
custom_fields.append((attr_name, type, default)) |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
model_schema = create_schema( |
| 105 |
meta_conf.model, |
| 106 |
name=name, |
| 107 |
fields=meta_conf.fields, |
| 108 |
exclude=meta_conf.exclude, |
| 109 |
optional_fields=meta_conf.fields_optional, |
| 110 |
custom_fields=custom_fields, |
| 111 |
base_class=cls, |
| 112 |
) |
| 113 |
model_schema.__doc__ = cls.__doc__ |
| 114 |
return model_schema |
| 115 |
|
| 116 |
return cls |
| 117 |
|
| 118 |
|
| 119 |
class ModelSchema(Schema, metaclass=ModelSchemaMetaclass): |
| 120 |
pass |
| 121 |
|
| 122 |
|
| 123 |
_is_modelschema_class_defined = True |