根据另一个表的值从一个表中选择数据

时间:2015-08-18 00:21:22

标签: python database flask sqlalchemy flask-sqlalchemy

主题表:

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

主题表:

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

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

我有一个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

那么为什么我会收到此错误以及如何解决此问题?感谢。

1 个答案:

答案 0 :(得分:0)

Topic.中删除额外的Topic.Subject.accountID.in_(usersID)

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()
)