I have a mapper on a table and I want to define a column_property which should select True or False whether the entity has some propertie or not:
mapper( Person, persons_table, properties = {
'administrator': column_property(
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
).label( 'administrator' )
)
} )
Is this something I can do? I’m more interested in this part: [True if roles_table.c.is_admin or roles_table.c.id == 1 else False], which lets me set a value to the column based on the condition.
Your SELECT-expression is actually a Python expression:
sqlalchemy.select()will see this as:since the column object
roles_table.c.is_adminwill evaluate toTruein 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 ofif ... else ...:In your case, however, there might be a much simpler solution.
PersonandRoleseem to have aN:1relation (one person has exactly one role). I assume there is aorm.relationshipPerson.roleto get a person’s role.Why don’t you just add a plain Python property: