Reputation: 26678
I am using sqlalchemy with a database that doesn't support subselects. What that means is that something like this wouldn't work (where Calendar
is a model inheriting a declarative base):
Calendar.query.filter(uuid=uuid).count()
I am trying to override the count
method with something like this:
def count(self):
col = func.count(literal_column("'uuid'"))
return self.from_self(col).scalar()
However, the from_self
bit still does the subselect. I can't do something like this:
session.query(sql.func.count(Calendar.uuid)).scalar()
Because I want all the filter information from the Query
. Is there a way I can get the filter arguments for the current Query
without doing the subselect?
Thanks~
Upvotes: 1
Views: 444
Reputation: 309
From the SQLAlchemy documentation:
For fine grained control over specific columns to count, to skip the usage of a subquery or otherwise control of the FROM clause, or to use other aggregate functions, use func expressions in conjunction with query(), i.e.:
from sqlalchemy import func
# count User records, without
# using a subquery.
session.query(func.count(User.id))
# return count of user "id" grouped
# by "name"
session.query(func.count(User.id)).\
group_by(User.name)
from sqlalchemy import distinct
# count distinct "name" values
session.query(func.count(distinct(User.name)))
Source: SQLAlchemy (sqlalchemy.orm.query.Query.count)
Upvotes: 1