Assuming a many to many relationship (sqlalchemy, python), how to avoid adding duplicates? -


the tables authors , books in many many relationship. book can have many authors. author has possibly written many books.

author_1 = author('dan') session.add(author_1) author_1.books = [paper('illuminati'), book('sacrileg')] session.commit() 

this adds 2 books , author database , links them. far fine. both columns (authors.name , books.title) in different tables unique.

let's add new author, , let's assume dan had writing illuminati.

author_2 = author('brownie') session.add(author_2) author_2.books = [paper('illuminati')] session.commit() 

this results in duplicate error! why that? have query paper('illuminati') first? if have whole list of books? have query every single 1 of them? or there automatic function, how sqlalchemy determine if entry there , link it?

this long version of @renatopp comment

this results in duplicate error! why that?

you create new book/paper similar 1 have in db. take set paper/book's name unique constraint

do have query paper('illuminati') first?

let's see said before

let's add new author, , let's assume dan had writing illuminati.

this new author helps dan write illuminati. same illuminati on db. code there means "brownie writes new book has same name dan's". there 2 books, hence duplication error.

if want "brownie helping dan", have him write the same book. dan's illuminati db, , tell brownie dan.

    # illuminati = dan's book db     author_2.books.append(illuminati) 

i change code there. correct me if im wrong, think meant adding book brownie, not removing books , give him book afterward (author_2.books = [paper('illuminati')])

what if have whole list of books? have query every single 1 of them?

that depends. new books? or existing books? maybe of them new? or dont know @ all?

you'll have check them, or try catching exception


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -