[英]SQLAlchemy Bidirectional Association Proxy
I'm trying to create a simple many to many relationship with a mapping table containing metadata about the relationship it represents with association proxies on both ends using SQLAlchemy. 我正在尝试使用映射表创建一个简单的多对多关系,该映射表包含有关它使用SQLAlchemy在两端的关联代理表示的关系的元数据。 However, I can't seem to get it to work.
但是,我似乎无法让它发挥作用。 Here's the toy example I've been working with to try to figure it 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 the creator
functions so I could avoid writing an __init__
that won't work for my actual use case (takes single argument), and included the creation of the FooBar
in each because I read in some of the documentation that the item being appended needs to already have a linking table instance associated with it. 我添加了
creator
函数,所以我可以避免编写一个__init__
,它不适用于我的实际用例(采用单个参数),并且在每个FooBar
中都包含了FooBar
的创建,因为我在一些文档中读到了要追加的项目需要已经有一个与之关联的链接表实例。 I'm sure I'm just missing something obvious (or maybe even trying to do something that just can't be done), but after much digging through the docs and Googling, I can't figure out why it doesn't work. 我确定我只是遗漏了一些显而易见的东西(或者甚至可能尝试做一些无法完成的事情),但经过大量挖掘文档和谷歌搜索,我无法弄清楚为什么它不起作用。 What am I doing wrong?
我究竟做错了什么?
Your problem lies in the creator
: It should return the new instance of FooBar
and not bar
or foo
: 你的问题在于
creator
:它应该返回FooBar
的新实例,而不是bar
或foo
:
def bar_creator(value):
return FooBar(bar=value)
And analogous for foo_creator
. 和
foo_creator
类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.