Hi!

I'm trying save or update a register in database after check if it's exists 
or not, the save part it's ok, but the update always show the same error:

 "FlushError: New instance <Category at 0x10a6aae90> with identity key 
(<class 'test.model.Category'>, (u'1',)) conflicts with persistent instance 
<Category at 0x10a6cbd50>"

I read about this here 
<http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html#merge-tips>
 but 
I'm a newbie and don't understand what I exactly have to do to correct 
this, any help is appreciate.

Models:

class Model(Base):
    __tablename__ = 'model'

    id = Column(String(5), primary_key=True)
    name = Column(String(255), nullable=False)
    category = relationship("Category", backref="model")

class Category(Base):
    __tablename__ = 'category'

    id = Column(String(1), primary_key=True)
    name = Column(String(255), nullable=False)
    model_id = Column(String(5), ForeignKey('model.id'))


Save or update:

try:
    model = session.query(Model).get(item['id'])

    categories = []
    for category in item['category']:
        ic = Category(id=category['id'], name=category['name'])
        categories.append(ic)

    if not model:
        im = Model(id=item['id'], name=item['name'], category=categories)
        session.add(im)
    else:
        model.category = categories
        model.name = item['name']
        # Error: FlushError: New instance <Category at 0x10a6aae90> with 
identity key (<class 'test.model.Category'>, (u'1',)) conflicts with persistent 
instance <Category at 0x10a6cbd50>
    session.commit()
except:
    session.rollback()
    raise
finally:
    session.close()

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to