如何标记文章并按日期排序文章?



我是flask的新手,我已经从admin发布了一篇文章。现在我想让用户标记一个帖子,他们可以存储标记的帖子。谁能帮我实现这个功能?这是我的models.py

class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
title = db.Column(db.Text, nullable=False)
content = db.Column(db.Text, nullable=False)
description = db.Column(db.Text, nullable=False)
image_file = db.Column(db.String(40), nullable=False, default='default.jpg')
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post('{self.date}', '{self.title}', '{self.content}')"

和my routes.py

@app.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
comments = Comment.query.filter(Comment.post_id==post.id)
form = CommentForm()
return render_template('post.html',post=post,comments=comments,form=form)

@app.route('/post/<int:post_id>/comment',methods=['GET','POST'])
@login_required
def post_comment(post_id):
post=Post.query.get_or_404(post_id)
form=CommentForm()
if form.validate_on_submit():
db.session.add(Comment(content=form.comment.data,post_id=post.id,author_id=current_user.id))
db.session.commit()
flash("Your comment has been added to the post","success")
return redirect(f'/post/{post.id}')
comments=Comment.query.filter(Comment.post_id==post.id)
return render_template('post.html',post=post,comments=comments,form=form)

,我也想知道我应该在表格中添加什么?我将非常感谢所有的答案。

由于一个用户可以标记多个帖子,而一个帖子可以被多个用户标记,因此我建议您使用(双向)多对多关系。在Post模型中再添加两列

class Post(db.Model):
tagged_users_id = db.Column(db.Integer, db.ForeignKey("user.id"))
tagged_users = db.relationship("User", backref="tagged_posts", foreign_keys=[tagged_users_id], uselist=True)

backref属性在User模型中创建了一个名为"tagged_post "的列,其中包含所有带标签的帖子的id作为列表。

给文章加标签或取消标签

post = Post()
user = User()
post.tagged_users.append(user)
post.tagged_users.remove(user)

访问带标签的文章

user.tagged_posts
[tagged_post_id_1, tagged_post_id_2...]
post.tagged_users
[tagged_user_id_1, tagged_user_id_2...]

最新更新