tortoise / tortoise-orm

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

Optional parameter in pydantic_model_creator does not work after upgrading to pydantic v2 #1551

Closed cary997 closed 4 months ago

cary997 commented 8 months ago

Describe the bug

升级至 pydantic v2 后 使用 pydantic_model_creator 创建 pydantic 模型时,pydantic_model_creator(optional=(xxx))不生效,字段 仍为必须填写

After upgrading to pydantic v2, when using pydantic_model_creator to create pydantic model, pydantic_model_creator(optional=(xxx)) does not take effect, and fields are still required.

To Reproduce

class AuthUsers(BaseModel):
    username = fields.CharField(max_length=32, unique=True)
    password = fields.CharField(max_length=128)
    nickname = fields.CharField(max_length=32)
    phone = fields.CharField(null=True, max_length=20, unique=True)
    email = fields.CharField(max_length=128, unique=True)

    class Meta:
        table = "auth_users"
        indexes = ("username", "user_status")

class UserUpdateRequest(pydantic_model_creator(
    cls=AuthUsers,
    name="UserUpdateRequest",
    exclude=("username", "password",),
    exclude_readonly=True,
    optional=("nickname", "email",)
))
image

Expected behavior 在UserUpdateRequest模型中,nickname和email应该为可选的,但实际为必填参数。在pydantic v1和tortoise-orm 0.19.3中是正常工作的

In the UserUpdateRequest model, nickname and email should be optional, but are actually required parameters. This is working fine in pydantic v1 and tortoise-orm 0.19.3

Additional context 我已经下载develop分支中的最新源码,仍然存在此问题,我在/tortoise/contrib/pydantic/creator.py文件中看到以下代码,当我添加了json_schema_extra["nullable"] = True时,工作正常

I have downloaded the latest source code in the develop branch and still have this problem, I see the following code in the /tortoise/contrib/pydantic/creator.py file and when I add json_schema_extra["nullable"] = True, it works fine

image image

我认为是pydantic v2迁移指南中描述的一些更改引起的 Pydantic 2.0 Migration Guide

I think it's caused by some changes described in the pydantic v2 migration guide Pydantic 2.0 Migration Guide

YuriFontella commented 5 months ago

Has this been resolved somehow?

abondar commented 4 months ago

Should be fixed in 0.21.0