I've got a simple User model, defined like so:
# models.py from datetime import datetime from myapp import db class User(db.Model): id = db.Column(db.Integer(), primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) date_updated = db.Column(db.DateTime()) def __init__(self, email, password, date_updated=None): self.email = email self.password = password self.date_updated = datetime.utcnow()
When I create a new User object, my date_updated
field gets set to the current time. What I'd like to do is make it so that whenever I save changes to my User object my date_updated
field is set to the current time automatically.
I've scoured the documentation, but for the life of me I can't seem to find any references to this. I'm very new to SQLAlchemy, so I really have no prior experience to draw from.
Would love some feedback, thank you.
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.
Creating and Dropping Database Tables create_all() creates foreign key constraints between tables usually inline with the table definition itself, and for this reason it also generates the tables in order of their dependency.
One of which is that Flask-SQLAlchemy has its own API. This adds complexity by having its different methods for ORM queries and models separate from the SQLAlchemy API. Another disadvantage is that Flask-SQLAlchemy makes using the database outside of a Flask context difficult.
Just add server_default
or default
argument to the column fields:
created_on = db.Column(db.DateTime, server_default=db.func.now()) updated_on = db.Column(db.DateTime, server_default=db.func.now(), server_onupdate=db.func.now())
I prefer the {created,updated}_on
column names. ;)
SQLAlchemy docs about column insert/update defaults.
[Edit]: Updated code to use server_default
arguments in the code.
[Edit 2]: Replaced onupdate
with server_onupdate
arguments.
date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With