Search code examples
pythonsqlalchemymany-to-manyflask-sqlalchemy

SQLAlchemy find only parents that contain specific children


I have the following many-to-many models:


class Association(db.Model):
    parent_id = db.Column(db.Integer, db.ForeignKey(
        'parent.id'), primary_key=True)
    child_id = db.Column(db.Integer, db.ForeignKey(
        'child.id'), primary_key=True)
    child = db.relationship("Child", back_populates="parents")
    parent = db.relationship("Parent", back_populates="children")


class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    children = db.relationship("Association", back_populates='parent', 
                               lazy='dynamic', cascade="save-update, merge, delete, delete-orphan")

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parents = db.relationship("Association", back_populates='child', 
                              lazy='dynamic', cascade="save-update, merge, delete, delete-orphan")

How can I get all parents that have the exact children ids in a list (Example: [5,6]) and no additional ids?


Solution

  • I ended up solving it using the following code:

    ids = [c1, c2, c3]
    q1 = Parent.query.filter(Parent.children.any(
    Association.child_id == c1)).filter(Parent.children.any(Association.child_id == c2))
    .filter(Parent.children.any(Association.child_id == c3))
    .filter(~Parent.children.any(Association.child_id.notin_(ids)))
    .all()
    

    But I am pretty sure there must be better ways to do this.