On Nov 19, 2007, at 9:49 AM, Thomas Wittek wrote:

>
> If you want to count the children of a parent entity you can do it
> like that:
>
>    parent.children.count(Child.id)
>
> Generally, this is fine. But it loads all children into the session
> and then "manually" counts them.
> For large sets this will become very slow.
>
> Wouldn't it be smarter to do the count in the database, as it would be
> done with the following query?
>
>
> session
> .query(Child).filter(Parent.id==Child.parent_id).count(Child.id)
>
> Currently I have to implement a children_count() method in the parent
> to avoid loading all the children from the database.

The "children" collection is nothing more than a plain Python list,  
which loads from the database the first time you access the  
attribute.  By the time the "count" method is accessed, the list is  
already loaded; this is currently how attribute instrumentation works.

To have it work differently, accessing parent.children when its not  
yet loaded would need to return some kind of proxy object, which when  
you then do something against the proxy object it then decides whether  
or not to populate.   The populate itself would then need to switch  
the attribute around, or perhaps remain in its proxied state.  We have  
done some experiments with this and its possibly something we might  
offer as an option in the future.   It might even be as easy as using  
a custom collection_class option, i.e.  
collection_class=ProxyCollection(list) or similar.  Id be hesitant  
making this the default, as our current collection behavior features  
the ability to deal directly with a native Python datastructure, with  
a minimal amount of "magic" going on.

Currently, there is the "dynamic" relation option where the collection  
on the read side is actually just a Query object set up with the join  
you have there, so that would produce this behavior right now, but  
then you arent dealing with a true collection.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
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