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

[QUESTION] Is there a way to specify fields to be optional in pydantic_model_creator?

Open ihsanmohamad opened this issue 5 years ago • 3 comments

As the title says, how do I make some fields optional using the pydantic_model_creator for my fastapi project? If there is no way, i would go with manual pydantic model. Thank you in advance.

ihsanmohamad avatar Nov 26 '20 12:11 ihsanmohamad

If you're after what I think you're after, pydantic_model_creator checks to see if your Tortoise database model has the null= set. By default, this is False (and thus the item is not optional) but it can be set to True and the resulting Pydantic model will be labeled as optional!

An example:

class OptionalExample(Model):
    optional = fields.IntField(description="An example of an optional field")
    not_optional = fields.IntField(description="An example of a non-optional field", null=True)

Which results in the following schema in FastAPI:

Screen Shot 2020-12-12 at 5 03 08 PM

timwford avatar Dec 13 '20 00:12 timwford

I would like the same for a PATCH method I'm writing. I want to be able to make all fields optional, even though none of the columns might be nullable, because the data from the Pydantic model gets applied on top of an existing valid model.

malikoth avatar Apr 17 '21 07:04 malikoth

If you're after what I think you're after, pydantic_model_creator checks to see if your Tortoise database model has the null= set. By default, this is False (and thus the item is not optional) but it can be set to True and the resulting Pydantic model will be labeled as optional!

An example:

class OptionalExample(Model):
    optional = fields.IntField(description="An example of an optional field")
    not_optional = fields.IntField(description="An example of a non-optional field", null=True)

Which results in the following schema in FastAPI:

Screen Shot 2020-12-12 at 5 03 08 PM

Isn't your example the other way around? In your code, you mention that adding null=True makes it non-optional field.

rsprudencio avatar Oct 26 '23 12:10 rsprudencio