Skip to content

Commit

Permalink
Adding the option to implement custom methods in abstract ModelSchema…
Browse files Browse the repository at this point in the history
… subclasses that cannot be instantiated and thus they don't have to undergo the strict checks that regular ModelSchemata need to fulfill.

Closes !62
  • Loading branch information
mikulas-mrva committed Nov 28, 2022
1 parent a63a146 commit 3fd4198
Show file tree
Hide file tree
Showing 4 changed files with 723 additions and 612 deletions.
9 changes: 9 additions & 0 deletions djantic/main.py
Expand Up @@ -57,6 +57,9 @@ def __new__(
f"{exc} (Is `Config` class defined?)"
)

if getattr(config, "abstract", False):
continue

include = getattr(config, "include", None)
exclude = getattr(config, "exclude", None)

Expand Down Expand Up @@ -165,6 +168,12 @@ class ModelSchema(BaseModel, metaclass=ModelSchemaMetaclass):
class Config:
orm_mode = True

def __init__(self, **data):
if getattr(self.Config, "abstract", False):
raise ConfigError("Abstract ModelSchema cannot be instantiated.")

super().__init__(**data)

@classmethod
def schema_json(
cls,
Expand Down
27 changes: 27 additions & 0 deletions docs/usage.md
Expand Up @@ -40,6 +40,33 @@ class UserSchema(ModelSchema):

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.

### Custom subclasses

Abstract subclasses can be defined to implement methods shared over for a number of ModelSchemata, note that they cannot be instantiated by themselves.

```python
from typing import Optional
from django.db.models import Model
from djantic import ModelSchema
from myapp.models import User

class BaseModelSchema(ModelSchema):
class Config:
model: Optional[Model] = None
abstract = True

def to_django(self) -> Model:
if self.Config.model is not None:
return self.Config.model.objects.create(**self.dict())
raise NotImplementedError()

class CreateUserSchema(BaseModelSchema):
class Config:
model = User

```


### Basic schema usage

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

0 comments on commit 3fd4198

Please sign in to comment.