【发布时间】:2014-07-28 22:27:19
【问题描述】:
我有两个模型,Word 和 Sentence,它们具有双向多对多关系。为了存储更多信息,我有一个关联对象,WordInSentence。
class WordInSentence(Base):
__tablename__ = "word_in_sentence"
word_id = Column(Integer, ForeignKey('word.id'),
primary_key=True)
sentence_id = Column(Integer, ForeignKey('sentence.id'),
primary_key=True)
space_after = Column(String)
tag = Column(String)
position = Column(Integer)
word = relationship("Word",
backref=backref("word_sentences", lazy="dynamic"))
sentence = relationship("Sentence",
backref=backref("sentence_words", lazy="dynamic"))
class Sentence(Base):
text = Column(Text, index = True)
words = association_proxy("sentence_words", "word",
creator=lambda word: WordInSentence(word=word))
class Word(Base):
word = Column(String, index = True)
sentences = association_proxy("word_sentences", "sentence",
creator=lambda sent: WordInSentence(sentence=sent))
def __repr__(self):
return "<Word: " + str(self.word) + ">"
我希望能够做这样的事情:
w = Word()
s = Sentence()
w.sentences = [s]
但是,我收到如下错误:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/plasma/project/venv/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py", line 274, in __set__
proxy.clear()
File "/home/plasma/project/venv/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py", line 629, in clear
del self.col[0:len(self.col)]
TypeError: object of type 'AppenderBaseQuery' has no len()
我还注意到文档中的this example,但我不确定如何使其成为双向和列表。
【问题讨论】:
标签: python sqlalchemy relationship