Skip to content

Instantly share code, notes, and snippets.

@MattOates
Created December 13, 2020 13:00
Show Gist options
  • Select an option

  • Save MattOates/7f8364f8da07c36874c0e9c2443dab19 to your computer and use it in GitHub Desktop.

Select an option

Save MattOates/7f8364f8da07c36874c0e9c2443dab19 to your computer and use it in GitHub Desktop.

Revisions

  1. MattOates created this gist Dec 13, 2020.
    41 changes: 41 additions & 0 deletions base.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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)