gpt4 book ai didi

python - SQLAlchemy - bool 混合属性

转载 作者:行者123 更新时间:2023-12-03 17:00:07 27 4
gpt4 key购买 nike

我希望能够运行以下 SQLAlchemy 查询:

q_done = Batch.query.filter(Batch.done)
q_running = Batch.query.filter(~Batch.done)

但我无法专心写 expression对应我的 done混合属性。

SQLAlchemy 模型:
class Action(db.Model):
id = db.Column(db.Integer, primary_key=True)
action = db.Column(db.String(32))
done = db.Column(db.Boolean, default=False)
batch = db.relationship(Batch.__name__, backref='actions')

class Batch(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), default='unknown')

@hybrid_property
def total_actions(self):
return db.session.query(Action).join(Action.batch).filter(Batch.id == self.id).count()

@hybrid_property
def finished_actions(self):
return db.session.query(Action).join(Action.batch).filter(Batch.id == self.id).filter(Action.done).count()

@hybrid_property
def done(self):
return self.total_actions == self.finished_actions

我尝试实现了相应的 expression没有太大的成功。很难理解如何返回 bool 查询。这是我卑微的尝试:
@done.expression
def done(self):
total_actions = db.session.query(func.sum(Batch.actions))
finished_actions = db.session.query(func.sum(Batch.actions.done))
return db.session.query(Batch).filter(total_actions == finished_actions)

最佳答案

问题是 total_actionsfinished_actions都是hybrid attributes因此不能在 expression 中使用对于 done .

我必须添加相应的expression对于每个返回查询而不是值的人。

这是完整的代码:

class Action(db.Model):
id = db.Column(db.Integer, primary_key=True)
action = db.Column(db.String(32))
done = db.Column(db.Boolean, default=False)
batch = db.relationship(Batch.__name__, backref='actions')

class Batch(db.Model):
id = db.Column(db.Integer, primary_key=True)

@hybrid_property
def total_actions(self):
return db.session.query(Action).join(Action.batch).filter(Batch.id == self.id).count()

@total_actions.expression
def total_actions(cls):
return (select([func.count(Action.id)]).
where(Action.bid == cls.id).
label("total_actions"))

@hybrid_property
def finished_actions(self):
return db.session.query(Action).join(Action.batch).filter(Batch.id == self.id).filter(Action.done).count()

@finished_actions.expression
def finished_actions(cls):
return (select([func.count(Action.id)]).
where(Action.bid == cls.id).
where(Action.done).
label("finished_actions"))

@hybrid_property
def done(self):
return self.total_actions == self.finished_actions

@done.expression
def done(cls):
return cls.total_actions == cls.finished_actions

关于python - SQLAlchemy - bool 混合属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com