Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Automatically Populate SQLAlchemy Database Fields? (Flask-SQLAlchemy)

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.

like image 515
rdegges Avatar asked Aug 28 '12 06:08

rdegges


People also ask

How do you update existing table rows in SQLAlchemy in Python?

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 db Create_all () do?

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.

What is difference between Flask-SQLAlchemy and SQLAlchemy?

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.


2 Answers

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.

like image 113
plaes Avatar answered Sep 22 '22 18:09

plaes


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()) 
like image 42
Savad KP Avatar answered Sep 22 '22 18:09

Savad KP