简体   繁体   English

SQLAlchemy中的关系外键过滤

[英]Filtering by relationship foreign key in SQLAlchemy

Say I have two SQLAlchemy models: Child and Parent .假设我有两个 SQLAlchemy 模型: ChildParent 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.我知道孩子与其父母( Child.parent )之间的关系,但我不知道用于链接这两个模型的实际外键

Using the relationship Child.parent , is there a simple way to find all children belonging to a certain Parent ?使用关系Child.parent ,有没有一种简单的方法可以找到属于某个 P 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' .例如,我希望能够做到这一点: Child.parent == 24 ,但它需要一个 model 实例在右侧,所以抛出'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:这种情况下可以先用select的父object的值,再确定属于这个父object的子列表:

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

based on a model definition for example like:基于 model 定义,例如:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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