【发布时间】:2019-03-10 23:11:54
【问题描述】:
所以我试图在我的代码中添加一个点赞按钮功能,允许用户喜欢特定的帖子。点赞将链接到登录用户,并显示点赞数。实现前端并不难,但我遇到了后端问题。
我是using this post here as a guide which does a follower system instead
这是我目前所拥有的?
我在 models.py 中为喜欢创建了一个表:
likers = db.Table('likers',
db.Column('liker_id', db.Integer, db.ForeignKey('post.id')),
db.Column('liked_id', db.Integer, db.ForeignKey('post.id'))
)
在我的用户类的 Models.py 中:
class User(db.Model, UserMixin):
#Code
liked = db.relationship(
'User', secondary=likers,
primaryjoin=(likers.c.liker_id == id),
secondaryjoin=(likers.c.liked_id == id),
backref = db.backref('likers', lazy='dynamic'), lazy='dynamic')
def like(self, post):
if not self.is_liking(post):
self.liked.append(post)
def unlike(self, post):
if self.is_liking(post):
self.liked.remove(post)
def is_liking(self, post):
return self.liked.filter(
likers.c.liked_id == post.id).count() > 0
在我的用户蓝图的 routes.py 中,我有:
@users.route("/like/<int:post_id>")
@login_required
def like(post_id):
post = Post.query.get_or_404(post_id)
current_user.like(post)
db.session.commit()
flash('Post has been liked')
return redirect(url_for('posts.post', post_id=post.id))
@users.route("/unlike/<int:post_id>")
@login_required
def unlike(post_id):
post = Post.query.get_or_404(post_id)
current_user.unlike(post)
db.session.commit()
flash('Post has been unliked')
return redirect(url_for('posts.post', post_id=post.id))
我做错了什么?我不断收到错误,例如:
builtins.KeyError
KeyError: 'likers'
我已经做了一个评论部分,我知道喜欢的关系将类似于 cmets,但我正在努力实现它。我对烧瓶比较陌生,我尝试过使用文档,但没有找到任何可以帮助我的东西......
这是我最后的希望。
【问题讨论】:
-
在您的“likers”表中,liker_id 的外键应引用 user.id,而不是 post.id。帖子不喜欢帖子,用户喜欢帖子。
-
@onosendi 我已经这样做了,但我仍然遇到问题
标签: python flask sqlalchemy flask-sqlalchemy