繁体   English   中英

Flask SQLAlchemy从外键关系中过滤记录

[英]Flask SQLAlchemy filter records from foreign key relationship

我有2个型号:

class Scenario(db.Model):
    __tablename__ = 'scenarios'
    scenario_id = db.Column(db.Integer, primary_key=True)
    scenario_name = db.Column(db.String(120))
    scenario_text = db.Column(db.Text)
    hints = db.relationship('Hint', backref='scenario', lazy='dynamic')

    def __init__(self, scenario_name, scenario_text):
        self.scenario_name = scenario_name
        self.scenario_text = scenario_text

    def __repr__(self):
        return "<Scenario(scenario_name='%s', scenario_text='%s', hints='%s')>" % self.scenario_name, self.scenario_text, self.hints

class Hint(db.Model):
    __tablename__ = 'hints'
    hint_id = db.Column(db.Integer, primary_key=True)
    scenario_id = db.Column(db.Integer, db.ForeignKey('scenarios.scenario_id'))
    hint = db.Column(db.Text)
    release_time = db.Column(db.Integer)    

    def __init__(self, scenario_id, hint, release_time):
        self.scenario_id = scenario_id
        self.hint = hint
        self.release_time = release_time

    def __repr__(self):
        return "<Hint(scenario_id='%s', hint='%s', release_time='%s')>" % self.scenario_id, self.hint, self.release_time

我希望能够获得具有相应提示的所有场景,但只能获得release_time小于当前时间的提示。

我认为这样可行:

scenarios = Scenario.query.filter(Scenario.hints.release_time < time.time())

但我得到这个错误:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Scenario.hints has an attribute 'release_time'

我刚开始玩Flask和SQLAlchemy。 任何意见,将不胜感激。

Scenario.hints是一个查询,因此您需要使用连接来执行此类过滤。

>>> scenarios = Scenario.query.join(Hint).filter(Hint.release_time < time.time())
>>> scenarios.first()
>>> <Scenario(scenario_name='hi', scenario_text='world', hints='SELECT hints.hint_id AS hints_hint_id, hints.scenario_id AS hints_scenario_id, hints.hint AS hints_hint, hints.release_time AS hints_release_time FROM hints WHERE :param_1 = hints.scenario_id')>

有关更多详细信息,请参阅查询文档ORM教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM