Reputation:
I use the below code of flask
test_flag = db.session.query(TestTable.flag).distinct()
It's SQL of [SQL: SELECT DISTINCT test_table.flag AS test_table_flag FROM test_table
flag
1
2
3
How to get a list value of db.session.query(TestTable.flag).distinct()
?
I need the output like this [1,2,3]
, what I want to do is to ensure whether 2 is in [1,2,3]
Upvotes: 0
Views: 728
Reputation: 55799
You can check for the value on the database side, without having to retrieve all the distinct values. This may be more efficient if you don't need all the values at the Python level, or if there are many rows in the table.
# Assuming there are rows containing 1, 2 and 3.
flags = db.session.query(True).filter(db.exists().where(TestTable.flag == 2)).scalar()
flags = db.session.query(True).filter(db.exists().where(TestTable.flag == 4)).scalar()
The first query will return True
, the second will return None
.
Similarly, you could query for the count of rows with the required value to see if any exist, but the exists construct is more efficient because it will stop searching after finding the first value that matches the filter.
Upvotes: 0
Reputation: 2923
You can use this to generate list of your flags
flag_list = [each.flag for each in db.session.query(TestTable.flag).distinct()]
Then you can use the below command to ensure whether 2
exist in flag_list
or not. If it does exist then it will return True
otherwise False
2 in flag_list
Upvotes: 0