fastapi / sqlmodel

SQL databases in Python, designed for simplicity, compatibility, and robustness.
https://sqlmodel.tiangolo.com/
MIT License
14.48k stars 661 forks source link

How to set check constraint in sql model? #292

Open christianholland opened 2 years ago

christianholland commented 2 years ago

First Check

Commit to Help

Example Code

pass

Description

SQLAlchemy allows to implement CheckContraint on either column or table level. How can I archive the same in SQLModel, e.g. limiting the possible values of a column to the colors red and green or to ensure that the values within a column are greater than 10.

I suppose it must be somehow possible using sa_column_kwargs (similar to implementing UniqueConstraint).

Help would be highly appreciated, thanks!

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.8.1

Additional Context

No response

jd-solanki commented 2 years ago

You can use various sa_column* args like:

jd-solanki commented 2 years ago

I use sa_column for Enum like below:

    access_status: EnumAccessStatus = Field(
        sa_column=Column(
            SaEnumAccessStatus,
            nullable=False,
        )
    )
dannyrohde commented 2 years ago

One caveat to using columns is that you might need to move properties like index or nullable into the Column description. I found that it otherwise doesn't get honoured.

E.g. the example in the above comment will work, but the below won't have the intended effect:

access_status: EnumAccessStatus = Field( sa_column=Column(SaEnumAccessStatus,), nullable=False, index=True)

LumaC0 commented 4 weeks ago

How about CheckConstraint at the table level? I've been setting it in __table_args__ like I'd do in sqlalchemy and just noticed Alembic isn't recognizing it.