SQLAlchemy Return All Distinct Column Values

后端 未结 4 2022
时光取名叫无心
时光取名叫无心 2021-02-07 10:45

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 SQLAlc

相关标签:
4条回答
  • 2021-02-07 10:46
    query = session.query(Class.title.distinct().label("title"))
    titles = [row.title for row in query.all()]
    
    0 讨论(0)
  • 2021-02-07 11:01

    Using the model query structure you could do this

    Class.query.with_entities(Class.title).distinct()
    
    0 讨论(0)
  • 2021-02-07 11:06

    As @van has pointed out, what you are looking for is:

    session.query(your_table.column1.distinct()).all(); #SELECT DISTINCT(column1) FROM your_table
    

    but I will add that in most cases, you are also looking to add another filter on the results. In which case you can do

    session.query(your_table.column1.distinct()).filter_by(column2 = 'some_column2_value').all();
    

    which translates to sql

    SELECT DISTINCT(column1) FROM your_table WHERE column2 = 'some_column2_value';
    
    0 讨论(0)
  • 2021-02-07 11:08
    titles = [r.title for r in session.query(Class.title).distinct()]
    
    0 讨论(0)
提交回复
热议问题