I like the first version better.

Apache OJB implements this with an intelligent list proxy class,
probably similar to SA's InstrumentedList. When asked for it's length,
the list checks if it's members have been loaded - and if not,
performs a "select count(*) ..." instead of loading all the objects.

Shouldn't something similar be possible with SA, using the __len__
override somewhere?

Arnar

On 8/3/06, Randall Smith <[EMAIL PROTECTED]> wrote:
> 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
>

-------------------------------------------------------------------------
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