【问题标题】:sqlalchemy paginationsqlalchemy 分页
【发布时间】:2011-09-11 01:42:11
【问题描述】:

我正在使用烧瓶和 sqlalchemy 构建一个 REST 应用程序,但遇到了一个问题。我想查询所有用户的书籍数量。每个用户都有很多书,所以我的查询应该返回每个用户在结果集中拥有的书数。

//      Models
class User( object ):
    __tablename__ = 'user'

class Book( object ):
    __tablename__ = 'book'

//      Metadata
users_table = Table( 'user', metadata,
    Column( 'id', Integer, primary_key = True ),
    Column( 'username', String( 50 ), unique = True )
)

books_table = Table( 'book', metadata,
    Column( 'id', Integer, primary_key = True ),
    Column( 'title', String( 50 ) ),
    Column( 'user_id', Integer, ForeignKey( 'user.id' ) )
)

//      Mappers
mapper( User, users_table, properties = {
    'booksCount': column_property( 
        select( 
            [func.count( books_table.c.id )],
            books_table.c.user_id == users_table.c.id
        ).label( 'booksCount' )
    ),
    'books' : relationship( Book )
} )

mapper( Book, books_table, properties = {
    'user': relationship( User )
} )

如果我想查询所有用户,它可以正常工作并返回与关联的“booksCount”相关的结果,但如果我想更深入,假设只查询“booksCount”大于 4 的用户,它就会变得复杂因为我还需要在应用限制/偏移之前知道总结果数才能使我的分页工作。

//  this works
rows = User.query
totalRows = rows.count ()
users = rows.limit( 50 ).offset( 0 ).all()

for user in users:
    ...

//  this throws an error
rows = User.query.having('booksCount>4')
totalRows = rows.count ()
users = rows.limit( 50 ).offset( 0 ).all()

第二个示例中此失败的原因是因为totalRows = rows.count () 创建了第二个查询来计算第一个结果:SELECT count(1) AS count_1 FROM user 但是当having 插入到查询中时,它会更改为SELECT count(1) AS count_1 FROM user having booksCount>4,这显然会上升错误,因为在第二次查询中从未选择过 booksCount。

那么,如何在应用了having 子句的选择中提取总行数?

谢谢。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    这实际上是一个sql语法错误。 having 子句仅在包含 group by 子句时使用,并且仅过滤聚合结果。您需要的是一个简单的where 子句,使用:

    rows = User.query.filter(User.booksCount > 4)
    

    附带说明:请按照 python 标准编写代码,例如User.books_count

    【讨论】:

    【解决方案2】:

    在相同情况下,我将用解决方案来回答我自己的问题。如果您在 ubuntu 上并从 repo 安装了 sqlalchemy,请将其卸载并转到 sqlalchemy 网站并按照他们的说明进行安装。新版本 (0.7.1 atm) 已修复此错误。

    Ubuntu 附带 0.6.4 版本。

    【讨论】:

    • 你没有解释你的代码的正确修改是什么。
    • 不知新版sqlalchemy不做二次查询了?
    猜你喜欢
    • 2017-08-23
    • 2013-08-30
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多