sch*_*lie 3 python sqlalchemy flask-sqlalchemy
我的SQL技能非常缺乏,所以我无法弄清楚如何形成我需要的查询.
我有两个具有一对多关系的db模型,定义如下:
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))
Run Code Online (Sandbox Code Playgroud)
我希望能够形成一个查询,返回满足三个条件的所有父母:
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'
Run Code Online (Sandbox Code Playgroud)
我只想要退回父亲#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)
Run Code Online (Sandbox Code Playgroud)
前两个条件工作正常.将关系设置为lazy ='join'允许我在关系上调用.any(),并获得我之后的结果.
但是,Condtion 3不能正常工作.它返回的父母有一个孩子不符合标准,而不是让所有孩子都不符合标准.
我已经搞乱了外部联接和其他执行此查询的方法,但我意识到我对SQL的了解不足以找出前进的方向.谁能指出我正确的方向?只知道我需要生成的SQL将是朝着正确方向迈出的一大步,但让它在SQLAlchemy中运行会很棒.
下面的查询应该这样做:
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)),
)
))
)
Run Code Online (Sandbox Code Playgroud)
几点:
or
条件-3NOT has any children...
(使用已完成~
)或者not
您使用的内容.条件-3的过滤器应该是:没有任何孩子满足bla-bla的父母,而你的代码暗示父母至少有一个不满足bla-bla的孩子.
归档时间: |
|
查看次数: |
1693 次 |
最近记录: |