[英]Fixing comment functionality for users to a post — flask app
我正在嘗試鏈接我的用戶,帖子和評論模型,以便在創建評論后,我希望能夠列出該帖子的所有評論(以及作者信息)。
在我的jinja2模板中:
{% for post in posts %}
{{ post.title }}
{{ post.content }}
{% for comment in post.comments %}
{{ comment.author.email }}
{{ comment.author.username }}
{{ comment.content }}
{% endfor %}
{% endfor %}
但是,我無法正確鏈接模型。 現在我有:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
...
posts = db.relationship('Post', backref='author', primaryjoin="User.id==Post.author_id")
comments = db.relationship('Comment', backref='author', primaryjoin="User.id==Comment.author_id")
def __repr__(self):
return "{}, {}, {}".format(self.username, self.email)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
content = db.Column(db.Text, nullable=False)
...
comments = db.relationship('Comment', backref='post', lazy=True)
def __repr__(self):
return "Post(Title:'{}', Content:'{}')".format(self.title, self.content)
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
def __repr__(self):
return "Comment({})".format(self.content)
但是,這不起作用。 在終端中嘗試時,post.comments返回“ []”(一個空列表)。 總體而言,模型關系給了我一個艱難的時期。
****編輯****這是我要查詢的方法之一的示例:
@app.route("/myposts", methods=['GET', 'POST'])
@login_required
def myposts():
page = request.args.get('page', 1, type=int)
user = User.query.filter_by(username=current_user.username).first_or_404()
posts = Post.query.filter_by(author=user)\
.order_by(Post.date_posted.desc())\
.paginate(page=page, per_page=5)
return render_template('myposts.html', title='My Posts', posts=posts, user=user)
獲得所有信息的一種方法是通過稍微更改查詢以使用顯式查詢:
posts = db.session.query(Post, User, Comments)\
.join(User)\
.join(Comments)\
.filter(Post.author==user)\
.order_by(Post.date_posted.desc())\
.paginate(page=page, per_page=5)
在這里,我假設User
和Comment
之間的關系不再存在。 但是,即使是這樣,也可以通過以下方式調試關系並更好地控制查詢:
1)看到由ORM生成的實際語句:
posts = db.session.query(Post, User, Comments)\
.join(User)\
.join(Comments)\
.filter(Post.author==user)\
.order_by(Post.date_posted.desc())
str(posts) # or posts.statement will print the query
2)使查詢更明確:
posts = db.session.query(
Post.id, Post.content, User.id, User.username,
Comments.date_posted, Comments.content.label('comm_content')
)\
.join(User)\ #you can even make this more explicit with .join(User, Post.author_id == User.id)
.join(Comments)\ #same as above
.filter(Post.author==user)\
.order_by(Post.date_posted.desc())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.