flask-sqlalchemy icon indicating copy to clipboard operation
flask-sqlalchemy copied to clipboard

How do I declare unique constraint on multiple columns?

Open xiangfeidongsc opened this issue 9 years ago • 2 comments

xiangfeidongsc avatar May 09 '17 23:05 xiangfeidongsc

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).

ThiefMaster avatar May 09 '17 23:05 ThiefMaster

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.
  • name is optional in the UniqueConstraint constructor, but it's a good practice to have it defined.

CristianoYL avatar Jun 25 '19 19:06 CristianoYL