On Dec 3, 2013, at 5:40 AM, Chung WONG <wch...@gmail.com> wrote:

> Hi all,
> 
> Say there are two tables defined as below:
> 
> class Topic(Base):
>     __tablename__ = 'topics'
>     id = Column(Integer,Sequence('topic_id_seq'), primary_key=True)
>     last_posted_at=Column(DateTime,default=func.now())
>     created_at=Column(DateTime,default=func.now())
>     posts=relationship('Post',backref='topic')
> 
> class Post(Base):
>     __tablename__ = 'posts'
>     id = Column(Integer,Sequence('post_id_seq'), primary_key=True)
>     topic_id=Column(Integer, ForeignKey('topics.id'), nullable=False)
>     created_at = Column(DateTime,default=func.now())
> 
> 
> Topic.last_posted_at  will get updated whenever a post is inserted, it is 
> basically the same as Post.created_at
> 
> Topic.last_posted_at won't get updated if flush() is not called, as 
> post.created_at does not exist yet.
> 
> 
> 
> post=Post()
> topic=DBSession.query(Topic).get(topic_id)
> topic.posts.append(post)
> DBSession.flush() # post.created_at now gets a value
> topic.last_posted_at=post.created_at
> 
> while this works, I am wondering is there any better way to achieve that?

use attribute append events to set the timestamp on both sides the same.  you 
can assign func.now() directly to the attribute if you want to rely upon the 
SQL function, if it were me I’d probably use a Python-side datetime.now() so 
it’s ready without having to go out to the database.

http://docs.sqlalchemy.org/en/rel_0_9/orm/events.html?highlight=append#sqlalchemy.orm.events.AttributeEvents.append
http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#embedding-sql-insert-update-expressions-into-a-flush




> 
> thanks in advance.
> 
> -- 
> 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/groups/opt_out.

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

Reply via email to