简体   繁体   中英

Flask SQLAlchemy query: filter records from self foreign key relationship

I have a model class with self ForeignKey relation like this:

class Foo(db.Model):
    id = Column(db.Integer, primary_key=True)
    name = Column(db.String(320))
    status = Column(db.Integer) # 0: undone, 1:done
    parent_id = Column(db.Integer, db.ForeignKey('foo.id'), index=True)
    parent = db.relationship(lambda: Foo, remote_side=id, backref='sub_foo')

I need to filter rows that have either no child or all done ( status == 1 ) children. In other words I need to exclude rows that have children with undone ( status == 0 ) status.

The easiest way to perform EXISTS queries is to use the any() and has() methods of relationships:

# Note the use of ~ operator for NOT
Foo.query.filter(~Foo.sub_foo.any(status=0))

any() accepts either SQL boolean expressions as positional arguments, or keyword arguments as shorthands for simple equality comparisons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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