Reputation: 1317
I have a SQLAlchemy db.Model class with a variable whose value I would like to update/reset during query access?
import datettime as dt
class MyEventCounter(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
daily_counter = db.Column(db.Integer, default=0)
last_updated_at = db.Column(db.DateTime, nullable=False,
default=dt.datetime.utcnow)
The daily_counter increases throughout the day, but updates/resets the following day.
Is there a way to update/reset the 'daily_counter' during the query (Ex: MyEventCounter.query.all() ) if the 'last_updated_at' was in the previous day? PS: Maybe something like a computed property
Upvotes: 0
Views: 522
Reputation: 4686
Yes, you should use a property. It should be as easy as:
from datetime import datetime as dt
@property
def counter(self):
if self.last_updated_at.date() < dt.now().date():
self.last_updated_at = dt.now()
self.daily_counter = 0
db.session.commit()
return self.daily_counter
Upvotes: 1