I ran into a not so unusual case today where I need a count of children 
for each parent in a one to many relationship.  I first thought of what 
I would do with SQL.  I would join the tables and use a COUNT aggregate. 
  Then I thought about how I might approach it with SQLAlchemy.  There 
is the select approach that is almost identical to the SQL approach and 
then there is the ORM approach.  I don't have many parent records, so I 
don't mind selecting them all, but I certainly don't want to select all 
of the child records.

     parents = session.query(Parent).select()
     counts = [len(parent.children) for parent in parents]

The problem with this is that len(parent.children) selects all of the 
child records (I think).  It would be nice if len(parent.children) 
triggered a COUNT instead.  Or maybe children could have a count method 
so it would look like this:

     parents = session.query(Parent).select()
     counts = [parent.children.count() for parent in parents]

Does a simple and efficient ORM approach already exist?  If not, what do 
you think of these two approaches?

Randall


-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys -- and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV
_______________________________________________
Sqlalchemy-users mailing list
Sqlalchemy-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/sqlalchemy-users

Reply via email to