AttributeError:'InstrumentedList'对象没有属性

Jon*_*Ong 8 python sqlalchemy pyramid

我有这些表格表:

class Thing(Base):
    __tablename__ = 'thing'
    id = Column(Integer, primary_key=True)

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)

class Voteinfo(Base):
    __tablename__ = 'voteinfo'
    thing_id = Column(Integer, ForeignKey('thing.id'), primary_key=True)
    thing = relationship('Thing', backref='voteinfo')
    upvotes = Column(Integer)
    downvotes = Column(Integer)

    def __init__(self, thing)
        self.thing = thing

class VoteThing(Base):
    __tablename__ = 'votething'
    id = Column(Integer, primary_key=True)
    voter_id = Column(Integer, ForeignKey('voter.id'))
    voter = relationship('Voter', backref='votescast')
    thing_id = Column(Integer, ForeignKey('thing.id'))
    thing = relationship('Thing', backref='votesreceived')
    value = Column(Boolean)

    def __init__(self, voter, thing, value):
        if value is True:
            thing.voteinfo.upvotes += 1
        else:
            thing.voteinfo.downvotes += 1
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我在"if value is True"子句中得到此错误代码:

AttributeError: 'InstrumentedList' object has no attribute 'upvotes'
Run Code Online (Sandbox Code Playgroud)

我试过给Voteinfo自己的唯一ID并在关系中添加uselist = False.我已经尝试将关系从VoteThing替换为Voteinfo,但这也无济于事.我不知道InstrumentedList是什么.到底是怎么回事?

mad*_*jar 16

正如文档中所解释的那样:https://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-one,你必须将uselist = False添加到关系中,而不是添加到backref .

thing = relationship('Thing', backref=backref('voteinfo', uselist=False))
Run Code Online (Sandbox Code Playgroud)

  • 对于那些阅读《The Future》这篇有用答案的人来说,backref() 现在是一个遗留功能:https://docs.sqlalchemy.org/en/20/orm/backref.html。看起来 uselist 位于关系标记的“多”侧:https://docs.sqlalchemy.org/en/20/orm/basic_relationships.html#setting-uselist-false-for-non-annotated-configurations (2认同)