SQLAlchemy, query Uuid column as str in coalesce

Question:

I have following query operation, which includes a Uuid column(sqlalchemy.Uuid) of a model. I need to convert it to a string and use in coalesce.

session
  .query(
    ...
    coalesce(MyModel.id, "").label(...)
    ...)
  .join(...)

I used str and function, but it didn’t work.
I want to get similar affect with COALESCE(my_models.id::text, ''). Is this possible with sqlalchemy query?

Asked By: rsar

||

Answers:

The values in coalesce must be of the same or related types. UUID and varchar / text are not sufficiently related, so we need to cast from UUID to text. The SQL could be

SELECT COALESCE(CAST(id, text), '') FROM tbl

or

SELECT COALESCE(id::text, '') FROM tbl

SQLAlchemy provides a cast function for this. Your query would be:

import sqlalchemy as sa
...
session.query(sa.func.coalesece(sa.cast(MyModel.id, sa.Text), '')...)

or in 2.0 style:

sa.select(sa.func.coalesece(sa.cast(MyModel.id, sa.Text), '')...)
Answered By: snakecharmerb
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.