与association_proxy的双向关系

Pla*_*sma 3 python sqlalchemy relationship

我有两个型号,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) + ">"
Run Code Online (Sandbox Code Playgroud)

我希望能够做到这样的事情:

w = Word()
s = Sentence()
w.sentences = [s]
Run Code Online (Sandbox Code Playgroud)

但是,我得到这样的错误:

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()
Run Code Online (Sandbox Code Playgroud)

我在文档中也注意到了这个例子,但我不确定如何使它成为双向和列表.

Aar*_*n D 9

您收到错误的原因TypeError: object of type 'AppenderBaseQuery' has no len()是因为您的关系设置为lazy="dynamic".如果您实际检查对象,它只是一个SQL查询.这就是为什么你不能迭代它 - 它必须首先执行.

您可以通过使用所有查询可用的标准函数来执行此操作 - 调用filter(<conditions>)对象,或者all()如果您需要所有查询.

如果您不希望每次访问时都执行动态查询的额外步骤,则另一个选项 - 如果关系中的子项数量不大 - 是将lazy设置更改为'select'.然后,这将在查询父对象的同时运行关联查询,这对于庞大的子数据库来说当然是不切实际的,但对于较小的数据库则不是不合理的.然后它可以按预期迭代.