Thanks Mike. I must admit I don't understand why that code works, but
it does. I guess that's the "Alchemy" in "SQLAlchemy" :-)

However, I have issues with the difference in NULL value semantics
between Python and SQL. Ie. if a calculated column is defined via a
column_property as price*amount, then the result will be NULL if any
of the values is NULL. However, in Python, None*something throws a
TypeError, so the hybrid_property getter function needs to be filled
with lots of IFs.

Also, this solution can't be used for date calculations, as timedelta
objects are needed. So I guess I will stick with a mix of Python
properties and column_properties.

On Jan 14, 4:23 pm, "Michael Bayer" <mike...@zzzcomputing.com> wrote:
> bojanb wrote:
> > Let's say I want to have a simple calculated property in my class, eg.
> > amount which is just qty * price.
>
> > I can define it as a column_property in a mapper which makes it
> > available in all database operations, eg. I can write session.query
> > (myclass).filter_by(amount>1000) which will create the correct WHERE
> > clause "qty*price>1000".
>
> > However, the attribute is None until the object is flushed to the
> > database, ie.
> > myclass.qty = 2
> > myclass.price = 500
> > print myclass.amount
>
> > will return None if flush was not issued.
>
> > If I use a Python property function to define it, it will be
> > immediately available (and always up to date); however, I cannot query
> > on a Python property.
>
> ultimately the value of this attribute is derived from other attributes
> which are mapped.   So there is a very simple and clever way to get both
> in that case which you can see if you look at
> examples/derived_attributes/attributes.py.
>
>
>
> > Is there a way to have best of both worlds? Or should I just define
> > the calculated property twice, eg. Python property named 'amount' and
> > a column_property named 'db_amount' and then work with the first but
> > use the second for querying?
> > --
> > You received this message because you are subscribed to the Google Groups
> > "sqlalchemy" group.
> > To post to this group, send email to sqlalch...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > sqlalchemy+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/sqlalchemy?hl=en.
-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.


Reply via email to