Is it possible to declare an optional and unique attribute for a class model in (Flask) SQLAlchemy?

StackOverflow https://stackoverflow.com/questions/23651806

Frage

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)

War es hilfreich?

Lösung

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)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top