这是我当前模型的简化示例(我正在使用Flask SQLAlchemy扩展):
like = db.Table(
'like',
db.Column('uid', db.Integer, db.ForeignKey('users.id')),
db.Column('pid', db.Integer, db.ForeignKey('posts.id'))
)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(20))
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(255))
likes = db.relationship(
'User',
secondary = like,
backref = db.backref('likes', lazy = 'dynamic'),
lazy = 'dynamic'
)
Run Code Online (Sandbox Code Playgroud)
我试图Post通过喜欢的数量订购.
这是我基本上试图发出的查询:
SELECT p.*, COUNT(l.`pid`) as `likes`
FROM `posts` as p
LEFT JOIN `like` …Run Code Online (Sandbox Code Playgroud) 我正在使用 Flask-SQLAlchemy 实现博客文章类型 Flask 应用程序。
我正在尝试根据每篇博客文章收到的点赞总数对博客文章进行排序。我尝试过将 SQLALchemy 混合属性与查询一起使用,session.query(Post).order_by(Post.likes_count.desc()).all()这类似于此处先前提出的问题的解决方案
它抛出错误AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Post.likes has an attribute 'count'
有没有一种方法可以使用需要提供给分页功能的喜欢计数来获取帖子顺序。
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20))
email = db.Column(db.String(120))
likes = db.relationship('Like', backref='user',lazy='dynamic',foreign_keys='Like.user_id')
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
date_posted = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
likes = db.relationship('Like', backref='post', lazy='dynamic')
@hybrid_property
def likes_count(self):
return self.likes.count()
def __repr__(self):
return …Run Code Online (Sandbox Code Playgroud)