tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.39k stars 359 forks source link

option to set validators of pydantic model #1471

Closed lucasbrahm closed 8 months ago

lucasbrahm commented 10 months ago

Pydantic provides Before, After, Wrap and Plain validators, Field validators and Model validators. This is nice for cleaning and validating fields. For example, you can remove any non numeric characters for a phone field and then validate, like this:

class Register(BaseModel):
    phone: str

    @field_validator('phone')
    @classmethod
    def validate_phone(cls, v: str) -> str:
        new_phone = re.sub(r'\D', '', v)
        if len(new_phone) < 7:
            raise ValueError('Invalid phone number')
        return new_phone

So both phone '123-4567' and '1234567' will be validated and it will be stored as '1234567'.

The problem of tortoise "pydantic_model_creator" is that it exposes few options when calling pydantic "create_model". Also, tortoise field validators only validate data, without modifying/cleaning data.

Fortunately, you can add validators in pyndatic by passing a dict to the "validators" argument when calling "create_model".

The idea of this PR is to add "validators" option in tortoise "pydantic_model_creator" which will be used during the call of pydantic "create_model"

So in the end it would be like this:

class Register(models.Model):
    phone = fields.CharField(max_length=20)

def validate_phone(v: str) -> str:
    new_phone = re.sub(r'\D', '', v)
    if len(new_phone) < 7:
        raise ValueError('Invalid phone number')
    return new_phone

validators = {
    'phone_validator': field_validator('phone')(validate_phone)
}

Register_Pydantic = pydantic_model_creator(Register, name="Register", __validators__=validators)
long2ice commented 8 months ago

Also please update changlog.

lucasbrahm commented 8 months ago

Made the adjustments. Also updated the docstring. Not sure how to add it to the changelog

long2ice commented 8 months ago

Just ref CHANGELOG.rst

lucasbrahm commented 8 months ago

Is it ok?

long2ice commented 8 months ago

Thanks!

coveralls commented 8 months ago

Pull Request Test Coverage Report for Build 6756606059

Warning: This coverage report may be inaccurate.

We've detected an issue with your CI configuration that might affect the accuracy of this pull request's coverage report. To ensure accuracy in future PRs, please see these guidelines. A quick fix for this PR: rebase it; your next report should be accurate.


Totals Coverage Status
Change from base Build 6502900700: 0.0%
Covered Lines: 5756
Relevant Lines: 6408

💛 - Coveralls