[英]SQLAlchemy func.count with filter
I'm using a framework that does pagination like this: 我正在使用一个像这样分页的框架:
def get_count_query(self):
return self.session.query(func.count('*')).select_from(self.model)
def paginate(self):
... <irrelevant>...
count = self.get_count_query.scalar()
...
I want to override the get_count_query method to use my own query because I'm filtering some results and get_count_query just returns all elements in the table. 我想覆盖get_count_query方法以使用我自己的查询,因为我正在过滤一些结果而get_count_query只返回表中的所有元素。 Queries are created dynamically, for example one query could be:
查询是动态创建的,例如,一个查询可以是:
Asset.query.join(StatusLabel).filter(StatusLabel.status == 'Deployable', or_(
Asset.assigned_to.isnot(None)),
Asset.deleted_at.is_(None))
I can count the elements in this query easily with query.count()
: 我可以使用
query.count()
轻松计算此查询中的元素:
def get_count_query(self):
q = Asset.query.join(StatusLabel).filter(StatusLabel.status == 'Deployable', or_(
Asset.assigned_to.isnot(None)),
Asset.deleted_at.is_(None))
return q.count()
But this will fail once it reach the .scalar() method (and I cannot remove this method). 但是一旦它到达.scalar()方法就会失败(我无法删除此方法)。 So the question is: how can I apply
func.count('*')
to an existing query? 所以问题是:如何将
func.count('*')
应用于现有查询?
Can I retrieve the filters from my query and apply them to the func.count('*')
query? 我可以从查询中检索过滤器并将它们应用于
func.count('*')
查询吗?
you can use select_from
with join
and filter
你可以使用
select_from
与join
和filter
def get_count_query(self):
return self.session.query(func.count('*')).select_from(Asset).join(StatusLabel)\
.filter(StatusLabel.status == 'Deployable', or_(
Asset.assigned_to.isnot(None),
Asset.deleted_at.is_(None)))
with subquery 与子查询
def get_count_query(self):
q = Asset.query.join(StatusLabel).filter(StatusLabel.status == 'Deployable', or_(
Asset.assigned_to.isnot(None)),
Asset.deleted_at.is_(None))
return self.session.query(func.count('*')).select_from(q.subquery())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.