python - Adding records in Many-to-Many relation cause duplicate error in sqlalchemy -
i have 2 tables: book
, author
, secondary table books_authors
, similar code:
book=book() author in authors: = author() a.books.append(book) session.merge(a) #1 session.merge(book) #2 session.commit()
this code cause error
sqlalchemy.exc.integrityerror: (integrityerror) (1062, "duplicate entry '1234' key 'id'") 'insert `book` (title, id) values (%s, %s)' ('test', u'1234')
i guess because merge made twice (#1, #2).
so decided remove #1
. errors not occurs, nil appears in table author. when decided remove #2
, tables book, author , books_authors fill in correctly, long 1 author added book.
more authors causes simillar previous error.
is normal #2
merge don't merge added authors? works in 1 direction? if yes, how not duplicate book entry merging 2 author entries?
i'm not familiar application code, gist of attempting should go this:
insert book record, if it's not there.
insert author record, if it's not there.
insert book_authors record if it's not there.
to prevent duplicate entries, utilize type of syntax.
insert yourtable (field1, field2, etc) select distinct value1, value2, etc some_small_table not exists (subquery check existing records)
depending on database engine, some_small_table part might not necessary.
python sql sqlalchemy many-to-many
No comments:
Post a Comment