1.模型类建立——peewee创建多对多关系表
1.1什么时候需要多对多关系表
由于,收藏表是帖子与用户表之间的关系,帖子表和用户表都已经完成创建了,因为这里是多对多的关系,所以需要建立关联表即可。并生成联合主键
1.2 代码展示
模型
# forum/models.py
# 用于创建数据表模型
from peewee import *
from forum import database
from datetime import datetime
# 创建基类:减少重复代码
class BaseModel(Model):
create_time = DateTimeField(default = datetime.now)
# 创建函数,用于返回用户的信息位字典形式
def to_json(self) -> dict:
r = {}
for k in self.__data__.keys():
# 判断数据是否是create_time(时间不是字符串)
if k == 'create_time':
r[k] = str(getattr(self,k))
else:
r[k] = getattr(self,k)
return r
class Meta:
database = database
# 创建用户表
class UserModel(BaseModel):
id = CharField(primary_key = True)
email = CharField(max_length=32, verbose_name='账号')
nick_name = CharField(max_length=32, verbose_name='昵称',null=True)
password = CharField(max_length=128, verbose_name='密码')
gender = CharField(verbose_name='性别',null=True)
signatrue = CharField(max_length=32, verbose_name='签名',null=True)
pic = CharField(max_length=512, verbose_name='头像',null=True)
status = CharField(verbose_name='账号状态', default=1)
class Meta:
table_name = 't_user'
# 创建帖子表
class TopicModel(BaseModel):
id = CharField(primary_key = True)
title = CharField(verbose_name='标题')
imgs = CharField(verbose_name='图片', max_length=2000)
content = CharField(verbose_name='内容',max_length=2000)
chick_num = CharField(verbose_name='点击数')
type_ = CharField(verbose_name='类型')
# 关联主表
user = ForeignKeyField(UserModel, backref='topics')
class Meta:
table_name = 't_topic'
# 创建收藏表——帖子表与用户表的关联表
class CollectionModel(BaseModel):
topic = ForeignKeyField(TopicModel, backref='collections')
user = ForeignKeyField(UserModel, backref='collections')
class Meta:
table_name = 't_collection'
primary_key = CompositeKey('topic','user') # 设置唯一主键
1.3效果展示
2.增加收藏——tornado增加接口
2.1查看前端需要的接口和传递的数据
2.2 代码展示
接口
# /forum/handler/CollecionHandler.py
from forum.handler.BaseHandler import BaseHandler
from forum import manager
from forum.models import TopicModel, UserModel, CollectionModel
from forum.decorators import login_required_async
# 增加收藏接口
class AddCollectionHandler(BaseHandler):
@login_required_async
async def post(self):
# 获取前端传递的文章id
topic_id = self.get_body_argument('id')
# 获取帖子信息
topic = await manager.get(TopicModel, id = topic_id)
# 通过验证登录装饰器获取登录用户id的用户信息
user = await manager.get(UserModel, id = self._user_id)
# 创建对象并保存
await manager.create(CollectionModel, topic = topic, user = user)
self.finish({'code':200,'msg':'收藏成功!!!'})
# 获取个人收藏接口
class GetMyCollectionHandler(BaseHandler):
@login_required_async
async def post(self):
# 通过userId获取收藏的信息
collection = await manager.execute(CollectionModel.select().join(UserModel).where(UserModel.id == self._user_id))
data = []
for c in collection:
tc = c.to_json()
tc['user'] = c.user.to_json()
tc['topic'] = c.topic.to_json()
del tc['topic']['user']
del tc['topic']['imgs']
del tc['topic']['content']
data.append(tc)
self.finish({'code':200,'msg':'获取个人收藏成功!','collection':data})
3.删除收藏——tornado删除接口
3.1 查看前端需要的接口和传递的数据
3.2代码展示
# /forum/handler/CollecionHandler.py
from forum.handler.BaseHandler import BaseHandler
from forum import manager
from forum.models import TopicModel, UserModel, CollectionModel
from forum.decorators import login_required_async
# 删除收藏接口
class DeleteMyCollectionHandler(BaseHandler):
@login_required_async
async def post(self):
topic_id = self.get_body_argument('id')
# 通过userid获取数据
user = await manager.get(UserModel, id = self._user_id)
# 通过topic获取帖子
topic = await manager.get(TopicModel, id = topic_id)
# 通过userid进行删除数据
rs = await manager.execute(CollectionModel.delete().where(CollectionModel.user == user, CollectionModel.topic==topic))
if rs > 0:
self.finish({'code':200, 'msg':'删除收藏成功!!!'})
else:
self.finish({'code':500, 'msg':'删除收藏失败!!!'})
4.首页模块_展示评论_收藏数
4.1概述
我们应该把他的评论数收藏数显示出来
4.2查看前端写的变量
4.3思路
首先,我们应该去前端代码中查看我们所需要返回的数据名称,由于我们已经开发过展示文章信息在主页的接口,所以,我们只需要在接口中添加两条添加数据的代码即可。
4.4代码展示
# 增加返回评论数
t['comment_num'] = topic.comments.count()
# 增加返回收藏数
t['like_num'] = topic.collections.count()