> On 24 Sep 2015, at 06:06, Hana Iku <[email protected]> wrote:
> 
> 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.

To clarify the error message: it means there is a Category instance in the 
session (loaded in python memory at 0x10a6cbd50) with the same primary key as a 
"new" Category object (at 0x10a6aae90). So the new category instance cannot be 
saved to the database. If it were, it would cause primary key conflict anyway.

What is going on? On the line "model.category = categories", the relationship 
"model.category" is loaded, so all Category rows in database with model_id == 
item['id'] are added to the session.

Then "model.category" is assigned, and the newly created Category instances are 
implicitly added to the session. Some of them however have the same primary key 
as some of the previously loaded instances.

It is not clear from your example what you are trying to achieve and why, but 
the simplest change to respect the apparent intent of you code (which may be 
different from what you actually intend to do) would be something like:

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

Conversely, you might want to omit specifying primary key of your category 
objects. In this case, there would be no primary key conflict, no need to use 
session.merge(), and the ForeignKey logic of SQLAlchemy would cause the old, 
now unused, Category rows to be deleted on session flush.

Regards.

-- 
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to