Stack Exchange
how to update many to many field sqlalchemy
I have two models, Publication and Article in a many to many relationship in SQLAlchemy with a postgres database.
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

publication_article_relation = Table("publication_article_relation", Base.metadata,
    Column("publication_id", ForeignKey('publication.id', ondelete="CASCADE", onupdate="CASCADE"), primary_key=True),
    Column("article_id", ForeignKey('article.id', ondelete="CASCADE", onupdate="CASCADE"), primary_key=True),
)

class Publication(Base):
    __tablename__ = "publication"
    id = Column(UUID(as_uuid=True), primary_key=True, index=True, nullable=False, default=uuid.uuid4)
    title = Column(Text, nullable=False)

class Article(Base):
    __tablename__ = "article"
    id = Column(UUID(as_uuid=True), primary_key=True, index=True, nullable=False, default=uuid.uuid4)
    publications = relationship("Publication", secondary=publication_article_relation, backref="article")
    description = Column(Text, nullable=False)

Now when I try to update it I do the following:
data = {
     description: "new description",
     publications: [SOME_UUID_1, SOME_UUID_2]
}


publications = []
for id in data.get("publications", []):
    pub = session.query(Publication).filter(Publication.id==id).one()
    publications.append(pub)

   
updated_record = {
     "description": data["description"],
     "publications": publications
}
session.query(Article).filter(Article.id==id).\
                update(updated_record, synchronize_session="fetch")

and I get the following error:
(builtins.TypeError) unhashable type: 'list'
[SQL: UPDATE article SET id = article_id AND id = publication_id=%(param_1)s, description=%(description)s WHERE article.id = %(id_1)s RETURNING article.id]
[parameters: [{}]]

If I remove data["publications"] it works, so I'm assuming it has to do with the publication_article_relation. What am I doing wrong here? Or what is the expected format for the "publications" field?

I found a different way to update it without the .update() method.
article = session.query(Article).filter(Article.id==id).one()
article.description = data.description
article.publications = publications
session.add(article)
session.commit()

That way I don't have to specify a special returning either to get the object.
