【问题标题】:AttributeError: 'InstrumentedList' object has no attributeAttributeError:“InstrumentedList”对象没有属性
【发布时间】:2011-12-02 01:57:06
【问题描述】:

我有这些表:

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 是什么。怎么回事?

【问题讨论】:

  • 因为thing__init__ 的一个参数,所以你可能在实例化VoteThing 时传递了它。那你通过什么?
  • 是的,我正在传递一个东西:thing1 = Thing(), user1 = User(), voteinfo1 = Voteinfo(thing1), votething1 = VoteThing(user1, thing1, True)

标签: python sqlalchemy pyramid


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    添加lazy='dynamic' 参数以请求不自动执行查询并当然刷新(thing = relationship('Thing', backref='voteinfo', lazy='dynamic'))可能很有用,否则会在内部发出表达式调用 all() 以返回“事物”列表' 因此 AttributeError: 'InstrumentedList' 对象没有属性错误!!

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2012-12-01
      • 2021-04-19
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多