Flask的 sqlalchemy 操作要点

1.filter和filter_by的区别

  filter,使用复杂的过滤条件,一般用两个等号进行匹配

  filter,使用简单的过滤条件,一般用一个等号进行匹配

Answer.query.filter(Answer.id == 1).first()
Answer.query.filter_by(id=1).first()

2.操作原生sql语句

sql = "select g_id, group_concat(id) from classify where g_id is not Null group by g_id;"
cursor = db.session.execute(sql)
result = cursor.fetchall()
cursor.close()

3.通过模型查询数据,获取特定的字段使用  with_entities,func. group_concat(字段名)根据分组结果,使用group_concat()来放置每一个分组中某字段的集合,having进行过滤。

result = Classify.query.with_entities(Classify.categories,  func.group_concat(Classify.id)).group_by('categories').having(Classify.g_id > 0).all()

 4. 获取特定字段的不重复数据,使用with_entities 和 distinct 。

Answer2Job.query.with_entities(Answer2Job.answer_id).distinct().all()   # 获取answer_id列不重复的数量
原文地址:https://www.cnblogs.com/pyweb/p/11844305.html