Skip to content
This repository was archived by the owner on Jul 18, 2024. It is now read-only.

Commit 820a991

Browse files
committed
Adding the option to implement custom methods in abstract ModelSchema subclasses that cannot be instantiated and thus they don't have to undergo the strict checks that regular ModelSchemata need to fulfill.
Closes !62
1 parent a63a146 commit 820a991

File tree

4 files changed

+723
-612
lines changed

4 files changed

+723
-612
lines changed

djantic/main.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ def __new__(
5757
f"{exc} (Is `Config` class defined?)"
5858
)
5959

60+
if getattr(config, "abstract", False):
61+
continue
62+
6063
include = getattr(config, "include", None)
6164
exclude = getattr(config, "exclude", None)
6265

@@ -165,6 +168,12 @@ class ModelSchema(BaseModel, metaclass=ModelSchemaMetaclass):
165168
class Config:
166169
orm_mode = True
167170

171+
def __init__(self, **data):
172+
if getattr(self.Config, "abstract", False):
173+
raise ConfigError("Abstract ModelSchema cannot be instantiated.")
174+
175+
super().__init__(**data)
176+
168177
@classmethod
169178
def schema_json(
170179
cls,

docs/usage.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,33 @@ class UserSchema(ModelSchema):
4040

4141
Once defined, the `UserSchema` can be used to perform various functions on the underlying Django model object, such as generating JSON schemas or exporting serialized instance data.
4242

43+
### Custom subclasses
44+
45+
Abstract subclasses can be defined to implement methods over for a number of ModelSchemata, not that they cannot be instantiated by themselves.
46+
47+
```python
48+
from typing import Optional
49+
from django.db.models import Model
50+
from djantic import ModelSchema
51+
from myapp.models import User
52+
53+
class BaseModelSchema(ModelSchema):
54+
class Config:
55+
model: Optional[Model] = None
56+
abstract = True
57+
58+
def to_django(self) -> Model:
59+
if self.Config.model is not None:
60+
return self.Config.model.objects.create(**self.dict())
61+
raise NotImplementedError()
62+
63+
class CreateUserSchema(BaseModelSchema):
64+
class Config:
65+
model = User
66+
67+
```
68+
69+
4370
### Basic schema usage
4471

4572
The `UserSchema` above can be used to generate a JSON schema using Pydantic's [schema](https://pydantic-docs.helpmanual.io/usage/schema/) method:

0 commit comments

Comments
 (0)