Skip to content

Instantly share code, notes, and snippets.

@MattOates
Created Dec 13, 2020
Embed
What would you like to do?
Attempt to make a nice Tortoise BaseModel to work with FastAPI
from typing import (
Type,
Optional,
)
from tortoise.models import Model
from tortoise.contrib.pydantic import (
pydantic_model_creator,
PydanticModel,
)
class pydantic:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.pydantic_model = None
def __set_name__(self, owner, name):
self.owner = owner
self.name = name
def __get__(self, instance: Optional[Model], typevar: Type[Model]) -> Type[PydanticModel]:
if instance is None:
if self.pydantic_model is None:
self.pydantic_model = pydantic_model_creator(
self.owner.__class__,
*self.args,
name=self.owner.__name__ + self.name.title(),
**self.kwargs
)
return self.pydantic_model
return self.pydantic_model
class BaseModel(Model):
All = pydantic()
Write = pydantic(exclude_readonly=True)
async def pydantic(self):
# TODO: get a type constraing on this
return await self.All.from_tortoise_orm(self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment