简体   繁体   中英

Filtering by relationship foreign key in SQLAlchemy

Say I have two SQLAlchemy models: Child and Parent . I know the relationship between the child and its parent ( Child.parent ), but I don't know the actual foreign key used to link the two models.

Using the relationship Child.parent , is there a simple way to find all children belonging to a certain Parent ?

For example, I'd like to be able to do this: Child.parent == 24 , but that expects a model instance on the right hand side, so throws 'str' object has no attribute '_sa_instance_state' .

You have a child-parent relationship with the key of the parent table as a foreign key in the child table. You don't know the name of the this key but the value. In this case you can select the parent object first with the value, and then determine the list of childs belonging to this parent object:

parentobject = Parent.query.get(24)
print(parentobject .childs)

based on a model definition for example like:

class Parent(db.Model):
  idunknown = db.Column(db.Integer, primary_key=True)
  childs = db.relationship('Child', backref='parent', lazy=True)

class Child(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  user_id = db.Column(db.Integer, db.ForeignKey('user.idunknown'), nullable=False)

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