flask-sqlalchemy
flask-sqlalchemy copied to clipboard
How do I declare unique constraint on multiple columns?
This is not the place to ask support questions. Also, considering that Flask-SQLAlchemy is a lightweight wrapper for SQLAlchemy check the SQLAlchemy docs, or ask in their mailing list, or in their IRC channel (#sqlalchemy on freenode).
For anyone having the same question, use the __table_args__ like so:
class UserModel(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), nullable=False)
email = db.Column(db.String(32), nullable=False)
__table_args__ = (
db.UniqueConstraint('username', 'email', name='uq_users_username_email'),
)
We define the unique constraint on users.username and users.email (doesn't make sense, but enough for demo).
Notice that:
__table_args__expects either a tuple or a dictionary.nameis optional in the UniqueConstraint constructor, but it's a good practice to have it defined.