python - SQLAlchemy Bidirectional Association Proxy -
i'm trying create simple many many relationship mapping table containing metadata relationship represents association proxies on both ends using sqlalchemy. however, can't seem work. here's toy example i've been working try figure out:
base = declarative_base() def bar_creator(bar): _ = foobar(bar=bar) return bar class foo(base): __tablename__ = 'foo' id = column(integer, primary_key=true) name = column(string) bars = association_proxy('bar_associations', 'bar', creator=bar_creator) def foo_creator(foo): _ = foobar(foo=foo) return foo class bar(base): __tablename__ = 'bar' id = column(integer, primary_key=true) name = column(string) foos = association_proxy('foo_associations', 'foo', creator=foo_creator) class foobar(base): __tablename__ = 'foobar' foo_id = column(integer, foreignkey('foo.id'), primary_key=true) bar_id = column(integer, foreignkey('bar.id'), primary_key=true) bazed = column(boolean) foo = relationship(foo, backref='bar_associations') bar = relationship(bar, backref='foo_associations') base.metadata.create_all(engine) make_session = sessionmaker(bind=engine) session = make_session() foo0 = foo(name='foo0') session.add(foo0) bar0 = bar(name='bar0') foo0.bars.append(bar0)
i added creator
functions avoid writing __init__
won't work actual use case (takes single argument), , included creation of foobar
in each because read in of documentation item being appended needs have linking table instance associated it. i'm sure i'm missing obvious (or maybe trying can't done), after digging through docs , googling, can't figure out why doesn't work. doing wrong?
your problem lies in creator
: should return new instance of foobar
, not bar
or foo
:
def bar_creator(value): return foobar(bar=value)
and analogous foo_creator
.
Comments
Post a Comment