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

pydantic升级v2后,pydantic_model_creator生成schema时optional字段还是需要必填 #1454

Open 1229984599 opened 10 months ago

1229984599 commented 10 months ago

Describe the bug 在v2版本中optional字段必须设置默认值后才会是选填 image

Expected behavior 希望可以添加default字段到代码中 image

Nautalis commented 10 months ago

I'm getting this issue as well. This is also my first Github issue, so please let me know if I'm doing anything wrong.

If I create a Tortoise model Manufacturer, like:

/app/models.py

class Manufacturer(Model):
    id = fields.IntField(pk=True)

    company_name = fields.CharField(max_length=50, unique=True)
    logo_url = fields.CharField(max_length=255, null=True)
    website_url = fields.CharField(max_length=255, null=True)

    def __str__(self):
        return self.company_name

Then use pydantic_model_creator to generate a Pydantic model from it, such as:

/app/schema.py

Tortoise.init_models(["app.models"], "models")

Manufacturer_Pydantic = pydantic_model_creator(Manufacturer, name="Manufacturer")

Then the Pydantic model that comes out the other end requires the logo_url and website_url fields, despite the documentation stating that the pydantic_model_creator function should read the null=True argument, and make the fields Optional accordingly.

1229984599 commented 10 months ago

你按照截图在413行的位置加上default这个参数就能正常使用了,由于作者还没有修复,我自己在外部重写了pydantic_model_creator来应急用 @Nautalis

long2ice commented 10 months ago

Thanks! Could you make a PR?

plusiv commented 8 months ago

@long2ice this one was solved with #1465