You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask SQLAlchemy筛选三个月内发布的博客文章

筛选Flask-SQLAlchemy中三个月内发布的博客文章

嘿,这个需求实现起来很顺畅,我给你两种靠谱的方案,你可以根据自己的场景选:

方案一:Python端计算时间阈值(直观易读)

我们先算出三个月前的当前时间,再用这个时间作为筛选边界。这里推荐用python-dateutil库的relativedelta来计算月份差,它能完美处理2月、31号这类特殊日期的边界情况,比原生timedelta靠谱多了。

操作步骤:

  1. 先装依赖(没装过的话):
pip install python-dateutil
  1. 编写查询代码:
from datetime import datetime
from dateutil.relativedelta import relativedelta
from your_app import db, BlogPost  # 替换成你实际的导入路径

# 计算三个月前的当前时间点
three_months_ago = datetime.now() - relativedelta(months=3)

# 筛选出发布日期在三个月内的文章
recent_posts = BlogPost.query.filter(BlogPost.date_posted >= three_months_ago).all()

执行后recent_posts就是你要的三个月内发布的文章列表。

方案二:数据库层面计算(高效适配大数据)

如果你的博客文章数据量很大,或者想让数据库直接处理时间逻辑,可以用SQLAlchemy的func调用数据库内置函数,把计算压力交给数据库:

from sqlalchemy import func
from your_app import db, BlogPost

# 让数据库直接计算三个月前的时间并筛选
recent_posts = BlogPost.query.filter(
    BlogPost.date_posted >= func.date_sub(func.now(), func.interval(3, 'month'))
).all()

这种方式不用额外装依赖,所有计算在数据库端完成,性能更优。

小细节提醒:你的模型有个小坑

看了你的BlogPost模型,发现date_posted的默认值写的是default=datetime.now()——这里的括号会导致模型定义时就执行一次datetime.now(),所有新创建的文章都会用这个固定时间,而不是创建时的实时时间!

正确写法要去掉括号,让SQLAlchemy每次创建实例时才调用函数:

date_posted = db.Column(db.DateTime, nullable=False, default=datetime.now)
# 更推荐用utcnow避免时区问题:
# date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

内容的提问来源于stack exchange,提问作者Daniele Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:07:37