我目前正在处理一个项目,我的数据库中有四个表 - 用户,主题,问题,答案。 每个用户都可以关注许多主题和问题,一个主题有很多关注者,一个问题有很多关注者和答案。此外,一个问题可能涉及多个主题。
现在我想在我关注的主题下找出所有答案,我希望按时间戳排序所有答案。我如何用flask-sqlalchemy来解决这个问题?我一整天都在上班,但找不到解决办法。
以下是代码:
class Question(db.Model):
__tablename__ = 'questions'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128), unique=True)
body = db.Column(db.Text())
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
timestamp = db.Column(db.DateTime(), default=datetime.utcnow)
followers = db.relationship('User',
secondary=questions_users,
backref=db.backref('questions_following', lazy='dynamic'),
lazy='dynamic')
answers = db.relationship('Answer', backref='question', lazy='dynamic')
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
email = db.Column(db.String(64), unique=True)
questions_asked = db.relationship('Question',backref='author', lazy='dynamic')
answers = db.relationship('Answer', backref='author', lazy='dynamic')
questions_users = db.Table('questions_users',
db.Column('question_id', db.Integer, db.ForeignKey('questions.id')),
db.Column('follower_id', db.Integer, db.ForeignKey('users.id')))
class Topic(db.Model):
__tablename__ = 'topics'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), unique=True)
description = db.Column(db.Text())
followers = db.relationship('User',
secondary=topics_users,
backref=db.backref('topics', lazy='dynamic'),
lazy='dynamic')
questions = db.relationship('Question',
secondary=topics_questions,
backref=db.backref('topics', lazy='dynamic'),
lazy='dynamic')
class Answer(db.Model):
__tablename__ = 'answers'
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.Text())
timestamp = db.Column(db.DateTime(), default=datetime.utcnow, index=True)
question_id = db.Column(db.Integer, db.ForeignKey('questions.id'))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
topics_users = db.Table('topics_users',
db.Column('topic_id', db.Integer, db.ForeignKey('topics.id')),
db.Column('user_id', db.Integer, db.ForeignKey('users.id')))
topics_questions = db.Table('topics_questions',
db.Column('topic_id', db.Integer, db.ForeignKey('topics.id')),
db.Column('question_id', db.Integer, db.ForeignKey('questions.id')))
答案 0 :(得分:0)
如果我理解正确,那么你可以简单地join along Answer's question - topics - followers,过滤和订购:
In [7]: db.session.query(Answer).\
...: join('question', 'topics', 'followers').\
...: filter(User.id == 1).\
...: order_by(Answer.timestamp)
由于多对多关系,结果集中可能会多次包含答案,但由于SQLAlchemy对单个实体查询进行了重复数据删除,因此这不是一个明显的问题。查询也可以使用EXISTS编写:
In [11]: db.session.query(Answer).\
...: join(Question).\
...: filter(Question.topics.any(
...: Topic.followers.any(
...: User.id == 1))).\
...: order_by(Answer.timestamp)