[QUESTION] Is there a way to specify fields to be optional in pydantic_model_creator?
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.
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:
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.
If you're after what I think you're after,
pydantic_model_creatorchecks to see if your Tortoise database model has thenull=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:
![]()
Isn't your example the other way around? In your code, you mention that adding null=True makes it non-optional field.