The Python Oracle

Sqlalchemy select condition

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Breezy Bay

--

Chapters
00:00 Sqlalchemy Select Condition
00:35 Accepted Answer Score 5
01:35 Thank you

--

Full question
https://stackoverflow.com/questions/7848...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sqlalchemy

#avk47



ACCEPTED ANSWER

Score 5


Your SELECT-expression is actually a Python expression:

select([True if roles_table.c.is_admin or roles_table.c.id == 1 else False],
       roles_table.c.id == persons_table.c.role_id)

sqlalchemy.select() will see this as:

select([True], some_expression_object)

since the column object roles_table.c.is_admin will evaluate to True in Boolean context. I don't know from the top of my head how SQLAlchemy will interpret this, but it will surely not work as you intended.

You will have to rewrite this expression so that it will correspond to plain SQL, using sqlalchemy.sql.expression.case() instead of if ... else ...:

column_property(
    select([case([(roles_table.c.is_admin, 1),
                  (roles_table.c.id == 1, 1)], else_=0)],
           roles_table.c.id == persons_table.c.role_id))

In your case, however, there might be a much simpler solution. Person and Role seem to have a N:1 relation (one person has exactly one role). I assume there is a orm.relationship Person.role to get a person's role.

Why don't you just add a plain Python property:

class Person:
    # ...

    @property
    def administrator(self):
        return self.role and (self.role.is_admin or self.role.id == 1)