On Oct 16, 2013, at 6:36 AM, Marcin Szamotulski <msza...@gmail.com> wrote:

> Hello,
> 
> I am trying to use onupdate context sensitive function and I came with the 
> following problem.
> I have a simple model
> 
> class Email(db.Model):
>     id = db.Column(db.Integer, primary_key=True, autoincrement=True)
>     email_number = db.Column(db.Integer, nullable=False)
>     body = db.Column(db.Integer, nullable=False)
>     updated = db.Column(db.TIMESTAMP, server_default=db.func.now(), 
> onupdate=on_update, nullable)
> 
> Where the on_update function (in Email.updated(onupdate=....) is:
> def on_update(context):
>     if 'body' in context.current_parameters:
>         now = datetime.datetime.now()
>         ts = context.current_parameters['updated'] = "{}-{}-{} 
> {}:{}:{}.{}".format(
>             now.year, now.month, now.day,
>             now.hour, now.minute, now.second,
>             now.microsecond,
>         )
>         return ts
>     else:
>         ts =  context.current_parameters['updated']
>         if ts is None:
>             now = datetime.datetime.now()
>             ts = context.current_parameters['updated'] = "{}-{}-{} 
> {}:{}:{}.{}".format(
>                 now.year, now.month, now.day,
>                 now.hour, now.minute, now.second,
>                 now.microsecond,
>             )
>         return ts
> 
> The reason for that is that I want to updated the Email.update only when the 
> Email.body has changed and not when Email.email_number is changing. But when 
> I change only the email_number the context contains:
> >>> context.current_parameters['updated']
> None
> 
> and not the current value updated field on the instance.

'updated' is None because you're inside of the "onupdate" function whose job it 
is to actually provide the value to be embedded into the UPDATE statement.   
current_parameters is a dictionary containing the parameters to be injected 
into the statement, not the current value of the row.

since you're using ORM your logic should be easier to implement as a 
before_update event, that event will give you the actual ORM instance being 
updated.  You can use history functions (e.g. 
inspect(instance).attrs.body.history ) to see what's changed on attributes and 
then assign to instance.updated at that point.


Attachment: signature.asc
Description: Message signed with OpenPGP using GPGMail

Reply via email to