This commit is contained in:
87
database/thottopic/crud.py
Normal file
87
database/thottopic/crud.py
Normal file
@ -0,0 +1,87 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from database.thottopic.model import THotTopic
|
||||
|
||||
|
||||
def create_hot_topic(db, hot_topic: THotTopic):
|
||||
db.add(hot_topic)
|
||||
db.commit()
|
||||
db.refresh(hot_topic)
|
||||
return hot_topic
|
||||
|
||||
|
||||
# 插入数据库之前判断数据库中是否已经存在,根据news.url 判断
|
||||
def create_topic_if_url_not_exists(db, hot_topic: THotTopic):
|
||||
# 检查是否已经存在具有相同 URL 的记录
|
||||
existing_topic = db.query(THotTopic).filter(THotTopic.url == hot_topic.url).first()
|
||||
|
||||
if existing_topic:
|
||||
# 如果记录已存在,直接返回已有的记录
|
||||
return existing_topic
|
||||
|
||||
# 如果记录不存在,插入新的记录
|
||||
db.add(hot_topic)
|
||||
db.commit()
|
||||
db.refresh(hot_topic)
|
||||
return hot_topic
|
||||
|
||||
|
||||
def create_topics_if_url_not_exists(db, topics: list[THotTopic]):
|
||||
inserted_topics = [] # 用于保存实际插入的新闻记录
|
||||
|
||||
for topic in topics:
|
||||
# 检查是否已经存在具有相同 URL 的记录
|
||||
existing_topic = db.query(THotTopic).filter(THotTopic.url == topic.url).first()
|
||||
|
||||
if not existing_topic:
|
||||
# 如果记录不存在,插入新的记录
|
||||
db.add(topic)
|
||||
inserted_topics.append(topic)
|
||||
|
||||
# 批量提交所有插入的记录
|
||||
db.commit()
|
||||
|
||||
# 刷新所有新插入的记录
|
||||
for topic in inserted_topics:
|
||||
db.refresh(topic)
|
||||
|
||||
return inserted_topics
|
||||
|
||||
|
||||
def get_hot_topic_by_id(db, hot_topic_id: int):
|
||||
return db.query(THotTopic).filter(THotTopic.id == hot_topic_id).first()
|
||||
|
||||
|
||||
def get_hot_topics(db, skip: int = 0, limit: int = 100):
|
||||
return db.query(THotTopic).offset(skip).limit(limit).all()
|
||||
|
||||
# 根据THotTopic.update_time排序,获取最新的THotTopic
|
||||
def get_latest_hot_topic(db):
|
||||
return db.query(THotTopic).order_by(THotTopic.update_time.desc()).first()
|
||||
|
||||
# 根据THotTopic.create_time获取今日的所有THotTopic
|
||||
def get_today_hot_topic(db):
|
||||
today = datetime.now().date()
|
||||
return db.query(THotTopic).filter(func.date(THotTopic.create_time) == today).all()
|
||||
|
||||
def update_hot_topic(db, hot_topic: THotTopic):
|
||||
db.merge(hot_topic)
|
||||
db.commit()
|
||||
db.refresh(hot_topic)
|
||||
return hot_topic
|
||||
|
||||
|
||||
# def update_hot_topic(db, hot_topic_id: int, updates: dict):
|
||||
# db.query(THotTopic).filter(THotTopic.id == hot_topic_id).update(updates)
|
||||
# db.commit()
|
||||
# return db.query(THotTopic).filter(THotTopic.id == hot_topic_id).first()
|
||||
|
||||
|
||||
def delete_hot_topic(db, hot_topic_id: int):
|
||||
hot_topic = db.query(THotTopic).filter(THotTopic.id == hot_topic_id).first()
|
||||
if hot_topic:
|
||||
db.delete(hot_topic)
|
||||
db.commit()
|
||||
return hot_topic
|
||||
Reference in New Issue
Block a user