tortoise / tortoise/tortoise-orm
Automatic conversion of validators in pydantic_model_creator
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
Is your feature request related to a problem? Please describe.
Consider the following example of a route using FastAPI:
class Person(Model):
name = fields.CharField(50)
age = fields.IntField(validators=[MinValueValidator(1)]
PersonSchema = pydantic_model_creator(Person)
@fast_api_app.post("/", response_model=PersonSchema)
async def create_person(data: PersonSchema):
p = Person.create(**data.dict())
return p
The PersonSchema does not contain the MinValueValidator. So the PersonSchema can hold an invalid age value, only throwing ValidationError when calling Person.create.
Describe the solution you'd like
I would like that pydantic_model_creator would create a model with the same validators as specified on the Tortoise Model.
Describe alternatives you've considered
I tried this:
def create_pydantic_model(model: Model, **kwargs):
schema = pydantic_model_creator(model, **kwargs)
for name, field in model._meta.fields_map.items():
validators = [Validator(v) for v in field.validators]
[setattr(v.func, "__name__", name + "_validator") for v in validators]
schema.__validators__[name] = validators
return schema
But Tortoise validators have this signature function(value: T) -> None and Pydantic validators are function(value: T) -> T, so they are kinda incompatible.
The final alternative was implementing an exception handler for Tortoise ValidationErrors.
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
The entry point is pydantic_model_creator; start by tracing how Tortoise model field validators are represented and how the generated schema is used in the FastAPI example. Add coverage showing that the generated schema rejects invalid values before Person.create; done when validators are carried into the schema without a separate exception handler.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- fastapi, python
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100