#models.py
#每日日期可以使用db.Date类型
#user_id和local_date使用了组合约束,只有当两个字段都相同时,才冲突
class StatDay(db.Model):
__tablename__ = 'statistics_days'
id = db.Column(db.Integer,primary_key=True)
user_id = db.Column(db.Integer, index=True)
clicks_count = db.Column(db.Integer,default=0)
local_date = db.Column(db.Date, unique=True,index=True)
#组合约束unique
__table_args__ = (db.UniqueConstraint('user_id', 'local_date', name='_user_id_local_date'),
)
#views.py
from datetime import datetime
@jump.route("/<key>")
def go_link(key):
#统计当日点击
#生成今日日期
local = datetime.now()
today = datetime.date(local)
#查询是否已经添加今日记录
stat_day = StatDay.query.filter_by(user_id=current_user.id,local_date=today).first()
if stat_day is None:#不存在则添加
stat_day = StatDay(user_id=current_user.id,
local_date=today,clicks_count=1)
else:#存在则+1
stat_day.clicks_count += 1
db.session.add(stat_day)
插入今日统计的行后,local_date这个字段通过shell查询出来时这样的:
>>> s=StatDay.query.first()
>>> s.local_date
datetime.date(2016, 10, 5)