Skip to content

Generatate composite unique constraints #1513

Answered by tadejsv
cacomop asked this question in Questions
Discussion options

You must be logged in to vote

Do this

from typing import Optional
import datetime
from sqlalchemy import UniqueConstraint
from sqlmodel import SQLModel, Field

class User(SQLModel):
    __table_args__ = (UniqueConstraint("name", "lastname"), )

    id: int = Field(primary_key=True)
    name: str = Field(unique=True)
    lastname: str = Field(unique=True)

UPD YuriiMotov: you probably don't need Field(unique=True) anymore. And don't forget teble=True:

from typing import Optional
import datetime
from sqlalchemy import UniqueConstraint
from sqlmodel import SQLModel, Field

class User(SQLModel, table=True):
    __table_args__ = (UniqueConstraint("name", "lastname"), )

    id: int = Field(primary_key=True)
    name: str
    

Replies: 9 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
7 participants
Converted from issue

This discussion was converted from issue #114 on August 13, 2025 10:42.