AttributeError:'InstrumentedList'对象没有属性

时间:2011-10-06 08:30:34

标签: 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

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

AttributeError: 'InstrumentedList' object has no attribute 'upvotes'

我尝试过为Voteinfo提供自己的唯一ID,并在关系中添加uselist = False。我已经尝试将这种关系从VoteThing替换为Voteinfo,但这也无济于事。我不知道InstrumentedList是什么。发生了什么事?

1 个答案:

答案 0 :(得分:13)

如文档中所述,此处:https://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-one,您必须将uselist = False添加到关系中,而不是添加到backref。

thing = relationship('Thing', backref=backref('voteinfo', uselist=False))