Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to create Column in SQLAlchemy which is going to be automatically populated with time when it inserted/updated last time?

Is it possible to create Column in SQLAlchemy which is going to be automatically populated with time when it inserted/updated last time ?

I created models, inherited from Base class

class Base(object):     def __tablename__(self):         return self.__name__.lower()     id = Column(Integer, primary_key=True)     last_time = Column(TIMESTAMP, server_default=func.now())  Base = declarative_base(cls=Base)  class EntityModel(Base):     __tablename__ = 'entities'     settlement_id = Column(Integer, ForeignKey('settlements.id'), nullable=False)     type = Column(String(20), nullable=False)     level = Column(Integer, nullable=False, default=0)     energy = Column(Float, nullable=False, default=0)     position_x = Column(Integer, default=0)     position_y = Column(Integer, default=0)      def __repr__(self):         return "<Entity('%s')>" % (self.type) 

Every time when I update EntityModel I want to the last_time be updated on system function.now(). I can do this on the database level with triggers but I would rather do on application level if is it possible.

like image 449
PaolaJ. Avatar asked Dec 20 '12 18:12

PaolaJ.


People also ask

How do I update a column in SQLAlchemy?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

What does back populate do SQLAlchemy?

The back_populates argument tells SqlAlchemy which column to link with when it joins the two tables. It allows you to access the linked records as a list with something like Parent.

What is Server_default in SQLAlchemy?

A client-side SQL expression, a server_default value, and server-side implicit defaults and triggers all have the server generate the default, which then must be fetched by the client if you want to be able to access it in the same SQLAlchemy session.

Does SQLAlchemy support batching?

SQLAlchemy supports the widest variety of database and architectural designs as is reasonably possible. Unit Of Work. The Unit Of Work system, a central part of SQLAlchemy's Object Relational Mapper (ORM), organizes pending insert/update/delete operations into queues and flushes them all in one batch.


1 Answers

In Base class add onupdate in the last statement as follows:

from sqlalchemy.sql import func  last_time = Column(TIMESTAMP, server_default=func.now(), onupdate=func.current_timestamp()) 
like image 170
tigeronk2 Avatar answered Sep 22 '22 02:09

tigeronk2