Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Return All Distinct Column Values

I am creating a website using Flask and SQLAlchemy. This website keeps track of classes that a student has taken. I would like to find a way to search my database using SQLAlchemy to find all unique classes that have been entered. Here is code from my models.py for Class:

class Class(db.Model):
    __tablename__ = 'classes'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    body = db.Column(db.Text)
    created = db.Column(db.DateTime, default=datetime.datetime.now)
    user_email = db.Column(db.String(100), db.ForeignKey(User.email))
    user = db.relationship(User)

In other words, I would like to get all unique values from the title column and pass that to my views.py.

like image 346
Paul Avatar asked Mar 08 '14 21:03

Paul


2 Answers

query = session.query(Class.title.distinct().label("title"))
titles = [row.title for row in query.all()]
like image 169
van Avatar answered Nov 18 '22 18:11

van


Using the model query structure you could do this

Class.query.with_entities(Class.title).distinct()
like image 29
Thomas Morrison Avatar answered Nov 18 '22 19:11

Thomas Morrison