Skip to content

Instantly share code, notes, and snippets.

@MattOates
Created December 13, 2020 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattOates/7f8364f8da07c36874c0e9c2443dab19 to your computer and use it in GitHub Desktop.
Save MattOates/7f8364f8da07c36874c0e9c2443dab19 to your computer and use it in GitHub Desktop.
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