SQLAlchemy: LIKE statement and user types

I am using sqlalchemy ORM. I have a custom column type and a table class:

class JSONEncodedDict(TypeDecorator):
    impl = VARCHAR

    def process_bind_param(self, value, dialect):
        if value is not None:
            value = json.dumps(value)

        return value

    def process_result_value(self, value, dialect):
        if value is not None:
            value = json.loads(value)
        return value

Base = declarative_base()
class Task(Base):
    __tablename__ = 'tasks'

    id = Column(INT, primary_key=True)
    description = Column(JSONEncodedDict)
    created = Column(TIMESTAMP)
    updated = Column(TIMESTAMP)

I want to query objcts using the 'like' operator:

tasks = session.query(Task).filter(Task.description.like("%some pattern%")).all()

But, as far as I see, the method process_bind_paramalso converts the operator parameter like. so in sql trace i see

...WHERE description LIKE '"%some pattern%"'

instead

...WHERE description LIKE '%some pattern%'

therefore no lines are matched.

How can I execute a query with an operator the likeway I want?

+4
source share
1 answer

You can bypass automatic type processing (or force your own argument type_) with literal():

Task.description.like(literal("%some pattern%"))
+3
source

All Articles