The other option in which you create the Column by hand with the sa_column param works, as did specifying __table_args__ = (UniqueConstraint("appid"),) as a class attribute for the table.
I think there's some logic in SQLAlchemy that dictates that when a column has an index the index actually gains the unique constraint. Can see more in the sqlalchemy Column docstring
Since all columns currently are created with an index by default in sqlmodel (see #11), we have to disable the index to see the unique constraint applied directly to the column.
Activity
obassett commented on Sep 1, 2021
To use unique you need to add the sa_column field bits and implement like SQL Alchemy does.
So in my case I wanted username to be a unique email address - so set it to a field set the column name, data type and added unique=True.
faris404 commented on Sep 2, 2021
@obassett It Works!! Thank you for your valuable time😊
raulolteanu-sudo commented on Sep 2, 2021
Related to this, how can you add Table Level Constraints to SQL Model ?
The equivalent of this in SQLModel:
rochacbruno commented on Sep 13, 2021
There is an easy way
rochacbruno commented on Sep 13, 2021
@raulolteanu-sudo you can write your custom data type with the validation as in https://pydantic-docs.helpmanual.io/usage/types/#custom-data-types
But note that this works in the programming level and not on SQL level.
danielbraun89 commented on Sep 13, 2021
sa_column_kwargs is amazing, havnt seen it anywhere in the docs. Thanks!
falkben commented on Nov 19, 2021
Just wanted to report that for me this did not work until I explicitly set index=False for the column. E.g.:
The other option in which you create the Column by hand with the sa_column param works, as did specifying __table_args__ = (UniqueConstraint("appid"),) as a class attribute for the table.
I think there's some logic in SQLAlchemy that dictates that when a column has an index the index actually gains the unique constraint. Can see more in the sqlalchemy Column docstring
Since all columns currently are created with an index by default in sqlmodel (see #11), we have to disable the index to see the unique constraint applied directly to the column.