2016-12-05 180 views
1
class Poll(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    title = db.Column(db.String(255), unique=False) 
    is_deleted = db.Column(db.Boolean, default=False) 
    created_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) 
    answers = db.relationship('Answer', backref='poll') 

class Answer(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    poll_id = db.Column(db.Integer, db.ForeignKey(Poll.id), nullable=False) 
    title = db.Column(db.String(255), unique=False, nullable=False) 
    votes = db.Column(db.Integer, nullable=False) 
    is_deleted = db.Column(db.Boolean, default=False, nullable=False) 
    created_date = db.Column(db.DateTime, default=datetime.datetime.utcnow) 

poll = PollModel.query.join(
    PollModel.answers 
).options(
    subqueryload(PollModel.answers.query) 
).filter(
    PollModel.id == poll_id, 
    PollModel.is_deleted == False, 
)[0] 

我想過濾由「is_deleted」屬性子查詢的相關答案。但是,我一直只會過濾民意調查是否有未刪除的答案。如何通過子查詢過濾相關對象。SQLAlchemy過濾器相關的子查詢

+0

我認爲你需要使用'contains_eager'來實現這一點。請看看這個選項的文檔。此外[這個答案](http://stackoverflow.com/a/7804059/99594)可能會有所幫助。 – van

回答

0

這項工作?

poll = Poll.query.filter(and_(Poll.id == poll.id, Poll.answers.any(is_deleted == False)).first()