On Mar 25, 2014, at 2:43 PM, Michael Robellard <m...@robellard.com> wrote:

> Hello, I have what seems like a simple problem, but the only solution I have 
> come up with so far isn't very good. I have a large complex query that is 
> hand optimized that is built from aggregates and other data from different 
> mapped tables. I can create a query for it by doing Session.query([column  
> names]).from_statement(query).params({}) and that works just fine, but rather 
> than each row being a KeyedTuple, I would like each row to be mapped to an 
> object of a class, so that I can create some properties and methods on the 
> object
> 
> When I tried 
> http://docs.sqlalchemy.org/en/rel_0_9/orm/mapper_config.html#mapping-a-class-against-arbitrary-selects
>  I get an error about not having a primary key defined
> 
> I did get this to kind of work with Bundles, but it looks ugly and you have 
> to dereference the bundle
> 
> Here's a gist of the code: 
> https://gist.github.com/subssn21/0f7300203aa39536ff5d
> 
> What's the right way to handle this?

the query you have there is entirely fixed.   You can map to this if you wanted 
(using mapper() with text())  but as this is read only and has no malleability 
at all, you might as well just map a dictionary to it:

class ShiftPunchData(object):
    def some_method(self):
        pass

    @classmethod
    def load_data(cls, session):
        for row in session.execute("  your big query goes here"):
            s = ShiftPunchData()
            s.__dict__.update(row)
            yield s

you'd get the same effect.   of course theres no relationships or eager loading 
or anything like that but you're working with an enormous fixed query so none 
of that applies anyway.

now if OTOH you want to build a flexible mapping based on that general query 
idea, you'd want to express most or all of it in terms of a SQL expression, 
either a core expression or ORM.   It depends on what you want to be able to do 
with it.



-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to