1. crud/news.py
python
async def get_related_news(db: AsyncSession, news_id: int, category_id: int, limit: int = 5):
"""
新闻详情-相关推荐
"""
stmt = (
select(News)
.where(
News.id != news_id,
News.category_id == category_id
)
.order_by(
News.views.desc(),
News.publish_time.desc()
)
.limit(limit)
)
result = await db.execute(stmt)
related_news = result.scalars().all()
return [
{
"id": item.id,
"title": item.title,
"content": item.content,
"image": item.image,
"author": item.author,
"publishTime": item.publish_time,
"categoryId": item.category_id,
"views": item.views
}
for item in related_news
]
2. routers/news.py
python
# 新闻详情-相关推荐
related_news = await news.get_related_news(
db,
news_detail.id,
news_detail.category_id
)
data = {
"id": news_detail.id,
"title": news_detail.title,
"description": news_detail.description,
"content": news_detail.content,
"image": news_detail.image,
"author": news_detail.author,
"publishTime": news_detail.publish_time,
"categoryId": news_detail.category_id,
"views": news_detail.views + 1,
"relatedNews": related_news
}
return Result.success(data)
完整代码
python
@router.get("/detail", response_model=Result)
async def get_news_detail(
news_id: int = Query(..., alias="id"),
db: AsyncSession = Depends(get_db)
):
"""
获取新闻详情、新闻浏览量 + 1、相关推荐
"""
# 获取新闻详情
news_detail = await news.get_news_detail(db, news_id)
if news_detail is None:
return Result.error(code=404, data="该新闻不存在")
# 新闻浏览量 + 1
news_res = await news.increase_new_views(db, news_id)
if not news_res:
return Result.error(code=404, data="更新浏览量失败")
# 新闻详情-相关推荐
related_news = await news.get_related_news(
db,
news_detail.id,
news_detail.category_id
)
data = {
"id": news_detail.id,
"title": news_detail.title,
"description": news_detail.description,
"content": news_detail.content,
"image": news_detail.image,
"author": news_detail.author,
"publishTime": news_detail.publish_time,
"categoryId": news_detail.category_id,
"views": news_detail.views + 1,
"relatedNews": related_news
}
return Result.success(data)