1

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~

synic
  • 26,359
  • 20
  • 111
  • 149

1 Answers1

1

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)

Christian
  • 279
  • 2
  • 8
  • Concerning filtering you can do: `query = session.query(func.count(Calendar.uuid)).filter(Calendar.uuid=='...')` – Christian Aug 26 '16 at 12:27
  • I know how to get the scalar. I want to override the ORM Query `count`. The first comment on my question is the answer. – synic Aug 26 '16 at 14:21