On Apr 23, 2007, at 3:49 PM, Gaetan de Menten wrote:

> Hello there,
>
> In a mapped object, is there any way to map a scalar attribute to an
> arbitrary selectable/subquery?
>
> Jonathan Ellis demonstrated how to do that for relations on this page:
> http://spyced.blogspot.com/2007/01/why-sqlalchemy-impresses-me.html
>
> I'd like to do that for scalars.
>
> I've thought about using a property returning a query, but this still
> generates one query per user (my mapped object) and I need to do
> everything in one pass.
>
> See attached file for an example of what I'd like to do.
>
> I've the feeling it might already be possible but I don't see how. If
> it's not possible yet, do you have any pointer how I could implement
> that?
>

there are probably three general ways to do what youre doing there.   
the oldest way is something i did in the zblog demo before SA 0.1 was  
released, which is that you map to the full query you want:

s = select([users_table, func.sum(tags_table.c.score1 *  
tags_table.c.score2).label('score')],  
users_table.c.user_id==tags_table.c.user_id, group_by=[c for c in  
users_table.c])

mapper(User, s)

the effect above is that your func() becomes another ColumnProperty.

the next way is to do it almost the same as Jonathan's blog says to  
do it, except youd map the relation to some intermediary class like  
"Score", and then use AssociationProxy to apply the "scalar" property  
to the class.   I might put a built-in feature in sa for "scalar"  
properties that does this, automatically creating an anonymous class  
for the intermediary....so that would be the closest to a "scalar  
relation".

the third way is not as slick but is to use add_column() on query:

session.query(User).join('tags').add_column(func.sum 
(tags_table.c.score1 * tags_table.c.score2).label('score'))).group_by 
([c for c in users_table.c])

which will give you back tuples of (User, int).




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