0

I tried to make the following query as a Pythonic chained comparison for filtering a range of inequalities:

minSalary = 0
maxSalary = 4000
results = Employee.query.filter(minSalary <= Employee.salary <= maxSalary).all()

But I got this error:

TypeError: Boolean value of this clause is not defined
Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
user5305519
  • 3,008
  • 4
  • 26
  • 44

1 Answers1

0

I was searching around to no avail but got inspired by this question and answer. I wanted to leave an answer or comment on said question, but thought this should be a separate question and answer instead.

Basically I thought that Pythonic compound statements are supported by SQLAlchemy (i.e. a

results = Employee.query.filter(minSalary <= Employee.salary).filter(Employee.salary <= maxSalary).all()
user5305519
  • 3,008
  • 4
  • 26
  • 44
  • SQLA cannot support that comparison, because it is transformed to `minSalary <= Employee.salary and Employee.salary <= maxSalary` behind the scenes by Python. The SQL way of doing that would be `Employee.salary.between(minSalary, maxSalary)`. – Ilja Everilä May 26 '20 at 06:32
  • Here's the detailed explanation of what goes on with chained comparisons: https://stackoverflow.com/questions/28754726/how-do-chained-comparisons-in-python-actually-work. – Ilja Everilä May 26 '20 at 06:38