繁体   English   中英

与association_proxy的双向关系

[英]Bidirectional relationship with association_proxy

我有两个模型, WordSentence ,它们具有双向的多对多关系。 为了存储其他信息,我有一个关联对象, 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()

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

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

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

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

希望这段代码可以帮到你。 我只是改变创建顺序并添加引擎和会话。 这是工作代码。

from sqlalchemy.engine import create_engine
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.schema import Column, ForeignKey
from sqlalchemy.sql.sqltypes import Integer, String, Float, Date

Base = declarative_base()

class Sentence(Base):
    __tablename__ = 'sentence'

    id = Column(Integer, primary_key=True)
    text = Column(String, index = True)

    sentence_words = relationship('WordInSentence')
    words = association_proxy("sentence_words", "word")

class Word(Base):
    __tablename__ = 'word'

    id = Column(Integer, primary_key=True)
    word = Column(String, index = True)

    word_sentences = relationship('WordInSentence')
    sentences = association_proxy("word_sentences", "sentence")

    def __repr__(self):
        return "<Word: " + str(self.word) + ">"


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"))


engine = create_engine('sqlite://')
Base.metadata.create_all(engine)

session = Session(engine)

测试:

>>> 
>>> w = Word(word='something new')
>>> w.sentences = [Sentence(text='there is somethine new')]
>>> session.add(w)
>>> session.commit()
>>> session.query(WordInSentence).one().word_id
1
>>> session.query(Word).one().word
'something new'
>>> session.query(Sentence).one().text
'there is somethine new'
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM