【问题标题】:Selecting data from one table based on the value of another根据另一个表的值从一个表中选择数据
【发布时间】:2015-08-18 00:21:21
【问题描述】:

科目表:

id | account_id | name
-------------------------
 8 |    112     | Biology

主题表:

id | subject_id | name
-------------------------
 1 |     8      | Plants

使用 Flask-SQLAlchemy,我想根据Subjects 表中account_id 的值从Topics 表中选择一行。

我有一个account_id 的列表,如下所示:users = [139, 193, 112, 028,],并且想选择这些用户的主题。

我试过了:

topicQuery = db.session.query(Topic).filter(Topic.Subject.has(Topic.Subject.accountID.in_(usersID))).all()

但收到错误AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Topic.Subject has an attribute 'accountID'

我认为这是我如何定义 Models.py 文件的问题,如下所示:

class Subject(db.Model):

    __tablename__ = 'subjects'

    id = db.Column(db.Integer, primary_key=True)
    accountID = db.Column(db.Integer, db.ForeignKey('accounts.id'))
    name = db.Column(db.String(100))
    Topic = db.relationship('Topic', backref=backref('Subject', cascade='delete'))

    def __init__(self, accountID, name):
        self.accountID = accountID
        self.name = name


class Topic(db.Model):

    __tablename__ = 'topics'

    id = db.Column(db.Integer, primary_key=True)
    subjectID = db.Column(db.Integer, db.ForeignKey('subjects.id', onupdate='CASCADE', ondelete='CASCADE'))
    name = db.Column(db.String(150))

    def __init__(self, subjectID, name):
        self.subjectID = subjectID
        self.name = name

那么为什么我会收到这个错误,我该如何解决这个问题?谢谢。

【问题讨论】:

  • print(028) 在你的 python 版本中做了什么?我认为它应该会产生错误。

标签: python database flask sqlalchemy flask-sqlalchemy


【解决方案1】:

从Topic.Subject.accountID.in_(usersID) 中删除多余的Topic.:

topicQuery = (
    db.session.query(Topic)
    .filter(Topic.Subject.has(Subject.accountID.in_(usersID)))
    .all()
)

或者,做一个简单的连接查询,这就足够了(而且可能更快):

topicQuery = (
    db.session.query(Topic)
    .join(Subject).filter(Subject.accountID.in_(usersID))
    .all()
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多