tortoise / tortoise/tortoise-orm
Is there a way to use regular Pydantic with Tortoise ORM
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
I am using the following model for both response body and request body.
- When using the pydantic created from tortoise as request body, pyright gives an error if I try to access model properties but the code works!
- I need the freedom to construct my own pydantic because sometimes I need specific fields.
- Some fields from the tortoise pydantic have validations which makes it hard to use them as request body. For example, below I had to override
idinUsersmodel in order to allow it to accept zero.
The point here it is very hard to combine request body and response body in pydantic model/models created from tortoise and impossible from regular pydantic as it cannot parse tortoise orm object if it is branching.
Is there away to make this easy or this is how it is?
or how about allowing a model with sub models to export a dictionary and just return it in the API. in that case I just need a pydantic for the request body.
Fields: TypeAlias = pydantic_model_creator(
models.Fields, name="Field_id", include=("id",)
)
UserRoles: TypeAlias = pydantic_model_creator(
models.UserRoles, name="UserRoles", include=("role_id",)
)
Users: TypeAlias = pydantic_model_creator(
models.Users, include=("id", "username", "name_first", "name_last", "mail")
)
class FieldId(Fields):
id: int
class UserRole(UserRoles):
fields: List[FieldId] = Field(default=[])
class User(Users):
id: Union[Literal[0], int] #because I need to allow it to accept zero
user_roles: List[UserRole] = Field(default=[])
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the shown pydantic_model_creator usage and reproduce the request/response and nested-model cases described. The issue is complete only once a supported way to use custom Pydantic request models with Tortoise-generated response models is established and its behavior is verified.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 15/100