I'm trying to create a sqlalchemy query (flask-sqlalchemy) that only returns parent objects if ALL children match the query instead of ANY. IE
(Parent
.query
.join(Child)
.filter(Child.column == True)
).all()
Will return all of the parent objects that have any child with column == True
, how do I write it so that all children must have column == True
?
The above portion was abstracted from this actual code. Where
Parent == Student and Child == StudentApplication
The model heirarchy goes:
User ---> Students ---> StudentApplication
I'm trying to retrieve users, who have students, who's application has not been submitted, while ignoring users who have at least 1 student with a submitted application.
def _active_student_query(statement=None):
import sqlalchemy as sa
statement = statement or _active_user_query()
statement = statement.join(Student).filter(Student.suspended == sa.false())
return statement
def users_without_submitted_applications(exclude_contacted=False):
import sqlalchemy as sa
from sqlalchemy.orm.util import AliasedClass
# AppAlias = AliasedClass(StudentApplication)
has_any_approved_app = sa.exists(
sa.select([])
.select_from(Student)
.where((StudentApplication.student_id == Student.id) &
(StudentApplication.flags.op('&')(AppFlags.SUBMITTED) > 0),
)
)
statement = _active_student_query()
statement = (statement
# .join(StudentApplication)
# .filter(User.students.any())
# has a student and no submitted applications
.filter(~has_any_approved_app)
# .filter(StudentApplication.flags.op('&')(AppFlags.SUBMITTED) == 0)
)
if exclude_contacted:
statement = (statement
.join(AlertPreferences)
.filter(AlertPreferences.marketing_flags.op('&')(MarketingFlags.NO_APP_PING) == 0)
)
from lib.logger import logger
logger.info(statement.sql)
return statement
And here's the SQL that it produces
SELECT users.is_active, users.flags, users.created_on, users.updated_on, users.id
FROM users JOIN student ON users.id = student.user_id
WHERE users.is_active = true AND student.suspended = false AND NOT (EXISTS (SELECT
FROM student_application
WHERE student_application.student_id = student.id AND (student_application.flags & %(flags_1)s) > %(param_1)s))
If you're looking for a parent where all children have column = TRUE
, then that is equivalent to all parents where no child has column = FALSE
. If you use a JOIN, you'd run into the problem of having one row per child, instead of per parent. Therefore, I'd recommend using WHERE EXISTS()
instead. A query like this would solve the problem:
SELECT *
FROM parent
WHERE NOT EXISTS(
SELECT
FROM child
WHERE child.parent_id = parent.id
AND child.column = FALSE
)
and in Flask-SQLAlchemy this becomes:
import sqlalchemy as sa
has_any_false_children = sa.exists(
sa.select([])
.select_from(Child)
.where((Child.parent_id == Parent.id) &
(Child.column == sa.false()))
)
Parent.query.filter(~has_any_false_children)
Update
Since you're talking about User
s where all Student
s have all StudentApplication
s completed, I think it should become
student_has_any_non_approved_app = sa.exists(
sa.select([])
.select_from(StudentApplication)
.where((StudentApplication.student_id == Student.id) &
(StudentApplication.flags.op('&')(AppFlags.SUBMITTED) > 0) &
((StudentApplication.flags.op('&')(AppFlags.APPROVED) == 0) |
(StudentApplication.flags.op('&')(AppFlags.PARTIALLY_APPROVED) == 0)))
)
user_has_any_non_approved_students = sa.exists(
sa.select([])
.select_from(Student)
.where((Student.user_id == User.id) &
(Student.suspended == sa.false()) &
student_has_any_non_approved_app)
)
statement = (
_active_user_query()
.filter(User.students.any())
# has a student and no submitted applications
.filter(~user_has_any_non_approved_students)
)
This will return all users. If you then want the students of that user, I'd put that into a separate query - and apply marketing flags there as well.
statement = Student.query.filter(
Student.user_id.in_(user_ids),
Student.suspended == sa.false()
)
if exclude_contacted:
statement = (statement
.join(AlertPreferences)
.filter(AlertPreferences.marketing_flags.op('&')(MarketingFlags.NO_APP_PING) == 0)
)
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.