How to define an Optional[Decimal] Field that yields to a constrained JSON schema #892
-
First Check
Commit to Help
Example Codefrom typing import Optional
from decimal import Decimal
from sqlmodel import SQLModel, Field
from sqlalchemy import Column, DECIMAL
class ItemBase(SQLModel):
...
price: Optional[Decimal] = Field(
default=None, ge=0, le=100, sa_column=Column(DECIMAL(7,4)),
regex=r"^\d+(\.\d+)?$" # added for the string part to only accept numbers
)
ItemBase.model_json_schema()
"""
{'properties': {'price': {'anyOf': [{'type': 'number'},
{'type': 'string'},
{'type': 'null'}],
'default': None,
'title': 'Price'}},
'title': 'ItemBase',
'type': 'object'}
""" DescriptionThe This problem also occurs on Pydantic, but there we can use In It is also frustrating to see the {type: string} in the json model for a decimal because it should be constrained with a regex or something to avoid passing pure text. But that is yet another problem and should be discussed in a pydantic thread instead. Operating SystemLinux, Windows Operating System DetailsNo response SQLModel Version0.0.16 Python Version3.9.13 Additional ContextI also created a stackoverflow question still waiting for an answer. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Look at the answer in stackoverflow. |
Beta Was this translation helpful? Give feedback.
Look at the answer in stackoverflow.