On Jun 28, 2010, at 5:23 AM, Sebastian Elsner wrote:

> Hello,
> 
> I build a query to filter a table depending on options a user can specify. So 
> I have a working query to execute when all GUI elements (which provide the 
> filter information) are evaluated.
> What I do is asking for the GUI elements value and depending on that I modify 
> the query:
> 
> class Project(Base):
>       __tablename__="Project"
>       id= Column(Integer,primary_keys=True)
>       status_id=Column(Integer)
> 
> q = sess.query(Project)
> 
> if checkbox:
>       q.filter(Project.id == 1)
> 
> if checkbox2:
>       q.filter(Project.id == 2)
> 
> ... and so on.
> 
> this works fine. Now I would like to provide the user with an overview on 
> what was filtered: So basically I want to use a group_by and count to show 
> how many Projects there are for each status_id. This is from the docs 
> (ormtut) and does what I want, except I want to apply this to an existing 
> query (or the result of one - don't care)
> 
> session.query(func.count(User.name),User.name).group_by(User.name).all()
> 
> 
> How would this be possible?

if from a SQL perspective you're looking for taking a query like "SELECT * FROM 
..." and turning it into "SELECT count(*) FROM (SELECT * FROM ...) GROUP BY 
...", i.e. turning it into a subquery, the from_self() method of Query is 
designed for that purpose, you might check the docs for that.

if OTOH you just want some ad-hoc columns from a Query, you can use values() 
for that.

http://www.sqlalchemy.org/docs/reference/orm/query.html?#sqlalchemy.orm.query.Query.from_self

http://www.sqlalchemy.org/docs/reference/orm/query.html?#sqlalchemy.orm.query.Query.values


It would be nice if all these methods had mini-examples at some point in the 
docs...

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to