TAGS :Viewed: 8 - Published at: a few seconds ago
[ Is it possible to declare an optional and unique attribute for a class model in (Flask) SQLAlchemy? ]
I just need to declare an attribute that is unique and optional. Is it possible in Python Sql Alchemy using Flask and Flask-SQLAlchemy?
membership_number = db.Column(db.String(120), unique=True)
Answer 1
If it is a primary key you can define it just as a primary_key
:
class MyModel(db.Model):
membership_id = db.Column(db.Integer, primary_key=True)
But if you need it to be unique apart from the primary_key use a UniqueContraint
class MyModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
membership_id = db.Column(db.String)
__table_args__ = (db.UniqueConstraint('membership_id'),)
or
membership_id = db.Column(db.String, unique=True)