帖子表:
class Post(UserMixin,db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer,primary_key= True)
timestamp = db.Column(db.String(20),index = True)
author = db.Column(db.Integer,db.ForeignKey("users.id"))
post = db.Column(db.String(500),index = True)
comments = db.relationship("Comment",backref = "post_id", lazy = "joined")
评论表:
class Comment(UserMixin,db.Model):
__tablename__ = "comments"
id = db.Column(db.Integer,primary_key = True)
comment_author_id = db.Column(db.Integer,db.ForeignKey("users.id"))
id_of_post = db.Column(db.Integer,db.ForeignKey("posts.id"))
timestamp = db.Column(db.String(60),index = True)
comment = db.Column(db.String(500),index = True)
comment_replies = db.relationship("Reply",backref = "comment_id",lazy = "dynamic")
用户表:
class User(UserMixin,db.Model):
__tablename__ = "users"
id = db.Column(db.Integer,primary_key = True)
username = db.Column(db.String(60),unique = True)
first_name = db.Column(db.String(60),index = True)
last_name = db.Column(db.String(60))
password = db.Column(db.String(100))
followed = db.relationship("Follow",foreign_keys = [Follow.followed_id],backref = db.backref("follower",lazy = "joined"),lazy = "dynamic")
follower = db.relationship("Follow",foreign_keys = [Follow.follower_id],backref = db.backref("followed", lazy = "joined"),lazy = "dynamic")
prof_pic =db.Column(db.String(40))
posts = db.relationship("Post",backref = "post_author", lazy = "joined")
comments = db.relationship("Comment", backref = "comment_author",lazy = "dynamic")
replies = db.relationship("Reply",backref = "reply_author",lazy = "dynamic")
所以我试图学习网络开发。因此,为了尝试理解事物,我决定去建立自己的小社交网络。只是为了获得关系数据库,瓶子和web dev的概念和想法
到目前为止一切顺利。 用户帖子按降序排列。首先看到最新的帖子。人们可以对这些帖子发表评论,然后就可以了解这些帖子。帖子以正确的方式排序,但评论不是。
它们在正确的帖子上发表了评论,但排序基于users.id
因此,如果我user1
并且我对user2's
发表评论,我的评论将优先于用户2发布,因为我user1
。
那么我们如何在sqlaclchemy中查询?
in pseudocode:
order posts by timestamp in descending order and order comments of post by timestamp in descending order
只需更改
即可解决此问题posts = db.relationship("Post",backref = "post_author", lazy = "joined")
到
posts = db.relationship("Post",backref = "post_author", lazy = "dynamic")