1

I'd like to update a row by sqlalchemy However I got this error.

sqlalchemy.orm.exc.StaleDataError: UPDATE statement on table 'ImgToolUser' expected to update 1 row(s); 2 were matched.

I run this code.

user = session.query(ImageToolUser).filter(ImageToolUser.key == key).first()
user.name = 'changed'
session. commit()

I checked sqlalcemy.engine log.

UPDATE `ImgToolUser` SET maker=%(maker)s, effect=%(effect)s WHERE `ImgToolUser`.mail = %(ImgToolUser_mail)s

This query was filtered by ImgToolUser.mail. This table has 2 row of same mail. So this error message showed 2 were matched..

My code is filtered by key. However this update query is filtered by mail. How should I change my code for update a row?

Solution

This question was closed. Because similar with other question. I found this questions solution. So, I'd like to share. How to solved this error.

I had mistake in ImageToolUser class.

I set primary_key on mail.

class ImageToolUser(Base):
    __tablename__ = "ImgToolUser"
    mail = Column(String(255), primary_key=True)
    name = Column(String(255))
    key = Column(String(255))

I should have set it on key.

class ImageToolUser(Base):
    __tablename__ = "ImgToolUser"
    mail = Column(String(255))
    name = Column(String(255))
    key = Column(String(255), primary_key=True)

I hope this Q&A helps for anyone.

Nori
  • 2,340
  • 1
  • 18
  • 41

0 Answers0