On Jan 31, 2011, at 12:46 PM, Alexander Zhabotinskiy wrote:
> Hello
>
> I want to get "today" orders of my user and I'm using relationship
> like:
>
> import datetime
> def now():
> return datetime.datetime.now()
> def time_from():
> return datetime.datetime(now().year, now().month, now().day)
> def time_to():
> return time_from() + datetime.timedelta(1)
>
>
> mapper(User, users_table,
> properties={'today_orders': relationship(Orders, primaryjoin =
>
> and_(orders_table.c.cashier_id==users_table.c.id,
> and_(orders_table.c.created>time_from(),
> orders_table.c.created<time_to()))
> ),
> )
>
> code works, but now() in my __init__ takes always the day of paster
> start date (when model have been initialized)
>
> What I'm doing wrong?
time_from() and time_to() are called immediately and hardwire a constant
timestamp into the primaryjoin.
One alternative is to use database functions to generate the dates, i.e.
"func.now()", "func.now() - 1", the latter assumes the target backend considers
integer subtraction from a date to be a day-based timedelta (Postgresql is the
only one I know that does it) - there are other versions of this function for
other backends (such as DATE_DIFF on SQL server).
Another alternative, is to use callables in the bind parameters. This is an
undocumented feature in 0.5, 0.6. In 0.7 the API changes, so make a note of
that if you go with this approach:
primaryjoin=and_(orders_table.c.created>lambda: time_from(),
orders_table.c.created<lambda: time_to())
Yet another way to do this which is more flexible, though a little more
complicated, is to feed the dates in as bind parameters explicitly. A recipe
to accomplish the pattern here, pretty much this exact use case, is at
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/GlobalFilter .
>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To post to this group, send email to [email protected].
> 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.
>
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
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.