Typing a column as : Optional[Decimal]
fails with "ValueError: Unknown constraint max_digits"
#791
-
First Check
Commit to Help
Example Codefrom decimal import Decimal
from typing import Optional
from sqlmodel import Field, SQLModel, create_engine
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
money: Optional[Decimal] = Field(default=0, max_digits=5, decimal_places=3)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def main():
create_db_and_tables()
if __name__ == "__main__":
main() DescriptionWith the example code from https://sqlmodel.tiangolo.com/advanced/decimal/#decimals-in-sqlmodel, replacing
Operating SystemLinux Operating System DetailsReproduced the issue within a python repl.it shell. SQLModel Version0.0.14 Python Version3.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 11 replies
-
@pellejacobs , I added Also: you may want to set the default to |
Beta Was this translation helpful? Give feedback.
-
On a similar problem, I'm dealing with a legacy SQL Server database that uses DECIMAL(18,0) fields as primary keys for its tables (don't ask, not my decision). As such, it seems that I can't type a primary key as from decimal import Decimal
from typing import Optional
from sqlmodel import Field, SQLModel, create_engine
class Hero(SQLModel, table=True):
id: Optional[Decimal] = Field(
default=None, primary_key=True, max_digits=18, decimal_places=0
)
name: str
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def main():
create_db_and_tables()
if __name__ == "__main__":
main() |
Beta Was this translation helpful? Give feedback.
-
@metamoof , have you tried just creating a fake column in the sqlmodel class def? I have a table that has no pk! I just lie and tell sqlmodel that there is another column that doesn't actually exist. |
Beta Was this translation helpful? Give feedback.
-
This discussion should not be marked as answered as the bug is still there. The stackoverflow page (https://stackoverflow.com/questions/78297135/how-to-define-an-optionaldecimal-field-in-python-sqlmodel-library-that-yields) received a temporary solution that suggests using le and multiple of instead of max_digits and decimal_places. @tiangolo |
Beta Was this translation helpful? Give feedback.
@pellejacobs , I added
nullable=True
to theField
parameters and it seems to work fine.Also: you may want to set the default to
None
if you want it to be optional. I don't think you have to, but it might be easier.