SQLAlchemy - 过滤查询,排除其中一个孩子符合条件的父项

时间:2015-06-04 15:51:14

标签: python sqlalchemy flask-sqlalchemy

我的SQL技能非常缺乏,所以我无法弄清楚如何形成我需要的查询。

我有两个具有一对多关系的数据库模型,定义如下:

class Parent(db.Model):
  __tablename__ = 'parent'

  id = db.Column(db.Integer, primary_key = True)

  children = db.relationship('Child', 
                             backref = 'parent', 
                             lazy = 'joined')

class Child(db.Model):
  __tablename__ = 'child'

  id = db.Column(db.Integer, primary_key = True)
  parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))

  value = db.Column(db.String(140))

我希望能够形成一个查询,返回满足三个条件的所有父母:

1:有一个或多个孩子,其值包含'value1'

2:有一个或多个孩子,其值包含'value2'

3:没有价值包含'value3'或'value4'

的孩子

对于此示例数据:

Parents:
id |
1  |
2  |
3  |
4  |

Children:
id | parent_id | value
1  | 1         | 'value1'
2  | 1         | 'value2'
3  | 1         | 'value3'
4  | 1         | 'value5'

5  | 2         | 'value1'
6  | 2         | 'value2'
7  | 2         | 'value4'
8  | 2         | 'value5'

9  | 3         | 'value1'
10 | 3         | 'value2'
11 | 3         | 'value5'
12 | 3         | 'value6'

13 | 4         | 'value1'
14 | 4         | 'value7'

我希望只返回父级#3。

就我而言:

from sqlalchemy import not_, and_

conditions = []

conditions.append(Parent.children.any(Child.value.ilike('%'+value1+'%'))
conditions.append(Parent.children.any(Child.value.ilike('%'+value2+'%'))

conditions.append(Parent.children.any(not_(Child.value.ilike('%'+value3+'%')))

condition = and_(*conditions)

q = db.session.query(Parent).filter(condition)

前两个条件正常。将关系设置为lazy ='join'允许我在关系上调用.any(),并获得我想要的结果。

但是,条件3不能正常工作。它正在回归有一个孩子不符合标准的父母,而不是让所有孩子都不符合标准。

我已经搞乱了外部联接和其他执行此查询的方法,但我意识到我对SQL的了解不足以找出要去的方向。谁能指出我正确的方向?只知道我需要生成的SQL将是朝着正确方向迈出的一大步,但让它在SQLAlchemy中运行会很棒。

1 个答案:

答案 0 :(得分:5)

下面的查询应该这样做:

q = (session.query(Parent)
     .filter(Parent.children.any(Child.value.ilike('%{}%'.format(value1))))
     .filter(Parent.children.any(Child.value.ilike('%{}%'.format(value2))))
     .filter(~Parent.children.any(
         db.or_(Child.value.ilike('%{}%'.format(value3)),
                Child.value.ilike('%{}%'.format(value4)),
                )
     ))
)

几点:

  • 条件-3
  • 需要or
  • 您还应该使用NOT has any children...(使用~完成)或使用内部的not

条件-3的过滤器应该是:父母没有任何孩子满足bla-bla ,而你的代码暗示父母至少有一个孩子不满足BLA-BLA