0

I'd like to achieve toggling a boolean flag with just one query.

My query looks as follows:

session.query(Foo).update({"status": SOME_NOT_OPERATOR})

Does SQLAlchemy supports PostgreSQL NOT (https://www.postgresql.org/docs/current/functions-logical.html) operator. How this can be achieved different way?

4
  • 1
    This question does not make sense. ... update({"status": SOME_NOT_OPERATOR}) is about setting a value not using an operator. If status is indeed a boolean type and you want to toggle it the: {"status": True} or {"status": False}. Commented Apr 22, 2022 at 21:25
  • Yeah but I just want to update the value to the opposite of what's currently stored in the db without additional query Commented Apr 22, 2022 at 21:26
  • 1
    @AdrianKlaver True, but you aren't capturing the toggle aspect. The OP wants status set to whichever value it isn't already, without having to query the value to decide whether to set it to True or False. Commented Apr 22, 2022 at 21:26
  • 2
    I don't have SQLAlchemy set up, so can't test. Maybe try {"status": ~Foo.status} per Invert. Commented Apr 22, 2022 at 21:42

1 Answer 1

1

As Adrian Klaver points out in their comment, SQLAlchemy's not_ operator will toggle the values. All of these statements are equivalent:

# 1.x style
session.query(Foo).update({'status': ~Foo.status})
session.query(Foo).update({'status': not_(Foo.status)})
# 2.0 style
session.execute(update(Foo).values(status=~Foo.status))
session.execute(update(Foo).values(status=not_(Foo.status)))

Will generate this SQL:

UPDATE foo SET status=NOT foo.status
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.