0

I have a SQL Alchemy mapping:

class Employee(Base):
  __tablename__ = 'employee'

  id = Column(Integer, primary_key=True)
  first_name = Column(String)
  last_name = Column(String)

  @hybrid_property
  def me(self):
    return 'Yes!' if self.first_name == 'ritratt' else 'Nope...'

Now I simply want to do a query like so: session.query(Employee.me).all()

But it does not work because SQL Alchemy expects a column or expression instead of a str. The solution is to use hybrid_expression but I do not want to use expressions. I want my mapping to only use hybrid property.

How can I write a mapping with a hybrid_property that returns a str and work with query()?

1 Answer 1

1

I found a hacky way around it. I use Python to derive the value and then wrap it either in cast or concat:

from sqlalchemy import cast, String

...

@hybrid_property
  def me(self):
    value = 'Yes!' if self.first_name == 'ritratt' else 'Nope...'
    return cast(value, String) # or return concat('', value)

This still seems a bit hacky. Wondering if a better way exists

Sign up to request clarification or add additional context in comments.

2 Comments

cast play good in this condition indeed ! another question is: can we use self.first_name to map a value ? So we can return sth like dict[self.first_name]
It seems self.first_name is not able to compare with string "ritratt"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.