tortoise-orm
tortoise-orm copied to clipboard
Invalid base class when using pydantic_model_creator
Describe the bug
When I have a tortoise.models.Model
and then convert it to a PydanticModel
using the pydantic_model_creator
function. It raises a mypy
error because it says that created class is not a valid base class
To Reproduce
from typing import Type
from uuid import UUID, uuid4
from pydantic.fields import Field
from tortoise import fields, models
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.contrib.pydantic.base import PydanticModel
class ProjectModel(models.Model):
id = fields.UUIDField( # noqa: A003, VNE003
pk=True, default=uuid4, description="Resource indentifier."
)
name = fields.CharField(
max_length=255, descirption="Project verbose name."
)
created = fields.DatetimeField(
auto_now_add=True, description="Timestamp resource has been created."
)
updated = fields.DatetimeField(
auto_now=True, description="Timestamp resource has been updated."
)
class Meta:
table = "projects"
ProjectPydantic: Type[PydanticModel] = pydantic_model_creator(
ProjectModel, name="Project"
)
class Project(ProjectPydantic): # raises the error
creator_id: UUID = Field(description="Project creator and owner.")
Expected behavior
The created class ProjectPydantic
should be a valid base class.
Try hinting using ProjectPydantic = pydantic_model_creator(ProjectModel, name="Project") # type: PydanticModel
instead. Not optimal but this works for me. Dynamic base classes in mypy are discussed here: https://github.com/python/mypy/issues/2477
Sorry, could you explain how to work with that and with mypy? Hinting it that way isn't working
This example produces errors in mypy https://tortoise-orm.readthedocs.io/en/latest/examples/fastapi.html
app/main.py:20: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
app/main.py:26: error: Variable "app.models.UserIn_Pydantic" is not valid as a type
app/main.py:26: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
app/main.py:27: error: UserIn_Pydantic? has no attribute "dict"
app/main.py:45: error: Variable "app.models.UserIn_Pydantic" is not valid as a type
app/main.py:45: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
app/main.py:46: error: UserIn_Pydantic? has no attribute "dict"
I had the same problem, and only using TypeAlias
and silencing mypy I was able to circumvent this issue and properly have code completion on VSCode.
from typing import TypeAlias
ProjectPydantic: TypeAlias = pydantic_model_creator(ProjectModel, name="Project") # type: ignore[misc]