On 06/15/2017 08:25 AM, 'mike waites' via sqlalchemy wrote:
> Hi
>
> This is something i've been wrestling in different ways for some time so
> i thought it was time that i sought a definitive answer on what the
> "proper" way to do this is with the ORM.
>
> Often you'll want to have some kind of scalar sub select that computes a
> column in your query. This can be achieved easily by doing the following
>
> |
> session.query(Model,scalar_sub_query).filter(...)
this is likely another candidate for:
https://bitbucket.org/zzzeek/sqlalchemy/issues/3058/allow-to-inject-expression-based-columns
which is theoretically the very last bug I am to fix for 1.2 which I am
feverishly trying to get done.
if you can try out the patch there and see if it applies to your use
case too, then that's another vote for me to do this one.
> |
>
> When passing additional column properties to the Query constructor like
> this results in SQLAlchemy giving you a named tuple back. In some cases
> this is fine but notice the first argument passed was Model, this is
> because we also want the ORM to do its normal thing of populating an
> instance of Model for us from the result of the query.
>
> In some cases this can be worked around by using declared_attr. This
> will allow us to define a field that is configured at import time from a
> function or something like that. This, in my experience, is suitable in
> rare occasions. The moment you need something that is not setup at
> import time makes this unsuitable. IE suppose your column requires a
> user id to figure out the result.
>
> The next thing that comes to mind is hybrid_property. This is a lot
> closer to what we want in most cases, the function is deferred until
> query time however, to my knowledge there's no way to have SQLAlchemy
> automatically populate a Model instance property from a hybrid_property
> which result in use coming back to the original problem. Specifying
> columns explicitly results in a named tuple when we simply want our
> model instance populated.
>
> There's no doubt a way to do this but i've given up trying to find it.
>
> Hope someone can help!
>
> --
> SQLAlchemy -
> The Python SQL Toolkit and Object Relational Mapper
>
>
http://www.sqlalchemy.org/
>
> To post example code, please provide an MCVE: Minimal, Complete, and
> Verifiable Example. See
http://stackoverflow.com/help/mcve for a full
> description.
> ---
> 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+...@googlegroups.com
> <mailto:
sqlalchemy+...@googlegroups.com>.
> <mailto:
sqlal...@googlegroups.com>.