Flask-SQLAlchemy .count() 和 .all() 的不同记录数 [英] Flask-SQLAlchemy different record count for .count() and .all()

查看:297
本文介绍了Flask-SQLAlchemy .count() 和 .all() 的不同记录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 SQLAlchemy 中,ModelName.query.filter_by(field_name=value).count() 返回正确的记录计数,但 ModelName.query.filter_by(field_name=value).all() 只返回一条记录.做一个 db.session.execute("SELECT * FROM table_name WHERE field_name = 'value'") 工作正常.有没有人遇到过类似的问题?有谁知道什么可能是错误的.任何指针都会有所帮助.

In SQLAlchemy, ModelName.query.filter_by(field_name=value).count() returns correct record count, but ModelName.query.filter_by(field_name=value).all() only returns a single record. Doing a db.session.execute("SELECT * FROM table_name WHERE field_name = 'value'") works fine. Has anybody faced a similar problem? Does anyone have any idea what could possibly be wrong. Any pointers will help.

可能有用的信息
我正在使用 MS SQL Server 2008 R2 并使用 FreeTDS/pyodbc 访问它.我不控制数据库,无法更改它.

Information that might be helpful
I am using MS SQL Server 2008 R2 and accessing it using FreeTDS/pyodbc. I do not control the database and can not change it.

提前致谢.

推荐答案

我想我可能遇到了同样的问题.我的查询执行多个连接,而不是原始结果可以带回同一主键的多行,每一行都由 .count() 计数,但是当您调用 .all() 时,主键上应用了一个不同的并且只有唯一的获取行,而不是 .all() 列表上的记录数与 .count() 不同.

I think I may have fallen in the same problem. My query do multiple Joins, than the raw result can bring back multiple rows of the same primary key, each row is counted by .count(), however when you call .all() a distinct is applied on the primary key and only unique rows are fetched, than the number of records on .all() list is different from .count().

这应该是相等的:

query.distinct().count() == query.all()

最好的问候

这篇关于Flask-SQLAlchemy .count() 和 .all() 的不同记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆