tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

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

Open 1229984599 opened this issue 2 years ago • 4 comments

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

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

1229984599 avatar Aug 19 '23 10:08 1229984599

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.

Nautalis avatar Aug 22 '23 00:08 Nautalis

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

1229984599 avatar Aug 22 '23 01:08 1229984599

Thanks! Could you make a PR?

long2ice avatar Aug 22 '23 01:08 long2ice

@long2ice this one was solved with #1465

plusiv avatar Oct 28 '23 02:10 plusiv