python - InvalidRequestError on ManyToMany relation with backref -


i've problem sqlalchemy m2m association. after adding backref relationship association, sqlalchemy throw error.

models:

assoc = table('foo_bars_assoc', db.metadata,      column('foo_id', integer, foreignkey('foo.id')),      column('bar_id', integer, foreignkey('bars.id')),      primarykeyconstraint('foo_id', 'bar_id', name='foo_bar_assoc_pk') )   class foo(db.model):     bars = relationship("bar", secondary="foo_bars_assoc")   class bar(db.model):     value = column(string, unique=true) 

i created get_or_create util method

def get_or_create(**kwargs):     entity = db.session.query(bar).filter_by(**kwargs).first()     if not entity:         entity = bar(**kwargs)         self.db.session.add(entity)         self.db.session.commit()     return entity 

let's suppose bars exist:

for i, bar in enumerate(foo.bars):     foo.bars[i] = get_or_create(value=bar.value) 

that method works well, until add reference m2m relationship.

error:

(psycopg2.integrityerror) duplicate key value violates unique constraint "bar_value_unique" 

can explain happened here? why after adding backref, sqlalchemy trying make inserts database ?


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -