You may use SQLAlchemy text and PostgreSQL array_append functions:
text('array_append(tags, :tag)')
For smallint type you may use PostgreSQL and SQLAlchemy type castings:
text('array_append(tags, :tag\:\:smallint)')
TestTable.tags.contains(cast((1,), TestTable.tags.type))
Examples:
Appending a value to an integer PostgreSQL array:
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine, Column, Integer, update, text
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class TestTable(Base):
__tablename__ = 'test_table'
id = Column(Integer, primary_key=True)
tags = Column(ARRAY(Integer), nullable=False)
engine = create_engine('postgresql://postgres')
Base.metadata.create_all(bind=engine)
DBSession = scoped_session(sessionmaker())
DBSession.configure(bind=engine)
DBSession.bulk_insert_mappings(
TestTable,
({'id': i, 'tags': [i // 4]} for i in range(1, 11))
)
DBSession.execute(
update(
TestTable
).where(
TestTable.tags.contains((1,))
).values(tags=text(f'array_append({TestTable.tags.name}, :tag)')),
{'tag': 100}
)
DBSession.commit()
Appending a value to a small integer PostgreSQL array:
from sqlalchemy import SmallInteger, cast
class TestTable(Base):
__tablename__ = 'test_table2'
id = Column(Integer, primary_key=True)
tags = Column(ARRAY(SmallInteger), nullable=False)
DBSession.execute(
update(
TestTable
).where(
TestTable.tags.contains(cast((1,), TestTable.tags.type))
).values(tags=text(f'array_append({TestTable.tags.name}, :tag\:\:smallint)')),
{'tag': 100}
)
Result:
id | tags
----+---------
1 | {0}
2 | {0}
3 | {0}
8 | {2}
9 | {2}
10 | {2}
4 | {1,100}
5 | {1,100}
6 | {1,100}
7 | {1,100}
session.add(user)is redundant.useris already insessionafter fetch, and is not transient to begin with.