4

I'm struggling to convert this to an ORM filter query:

select count(*) from issues WHERE pending_notifications ? 'flooby';

pending_notifications is a JSONB field containing a simple JSON array.

I'm not sure how to structure the filter using the question mark operator

I believe a Postgres ARRAY would work like this:

query.filter(pending_notifications.any('flooby'))

But I'm using JSONB and the filter syntax is not the same.

Any suggestions

3 Answers 3

4

You can use the .op() method to use any verbatim operator:

query.filter(pending_notifications.op("?")("flooby"))
Sign up to request clarification or add additional context in comments.

Comments

3

Given that you're using JSONB as column data type, use the has_key() method:

query.filter(pending_notifications.has_key('flooby'))

which maps to the ? operator. The method name is misleading in this context, but PostgreSQL documentation for jsonb operators describes ? thusly:

Does the string exist as a top-level key within the JSON value?

and so has_key() is somewhat aptly named.

An example:

In [21]: t = Table('t', metadata, Column('json', postgresql.JSONB))

In [28]: print(t.c.json.has_key('test'))
t.json ? :json_1

Comments

0

I can use raw sql in filter

from sqlalchemy import text

db.session.query(Issue).filter(text("pending_notifications ? 'flooby'")

Comments

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.