I’d like to achieve toggling a boolean flag with just one query.
My query looks as follows:
JavaScript
x
2
1
session.query(Foo).update({"status": SOME_NOT_OPERATOR})
2
Does SQLAlchemy supports PostgreSQL NOT (https://www.postgresql.org/docs/current/functions-logical.html) operator. How this can be achieved different way?
Advertisement
Answer
As Adrian Klaver points out in their comment, SQLAlchemy’s not_ operator will toggle the values. All of these statements are equivalent:
JavaScript
1
7
1
# 1.x style
2
session.query(Foo).update({'status': ~Foo.status})
3
session.query(Foo).update({'status': not_(Foo.status)})
4
# 2.0 style
5
session.execute(update(Foo).values(status=~Foo.status))
6
session.execute(update(Foo).values(status=not_(Foo.status)))
7
Will generate this SQL:
JavaScript
1
2
1
UPDATE foo SET status=NOT foo.status
2