python - 属性错误 : 'InstrumentedList' object has no attribute

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

最佳答案

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

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

关于python - 属性错误 : 'InstrumentedList' object has no attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7671886/

相关文章:

python - ReferenceProperty 是否有可能不生成反向引用的原因?

python - 使用 SQLAlchemy 元数据 reflect() 如何获得实际的表对象?

python - 在 sqlalchemy 查询中使用 jsonb_array_elements

python - Pyramid 1.4 需要 WebOb 1.2b3+。 Google App Engine 提供 WebOb 1.1.1。难道这一切都要以泪水结束吗?

session - 更新了 Pyramid 模型目录结构,现在 session 已损坏

python - 如何将标题映射到 Pandas 中的列?

python - 从三个列表中绘制热图 : X, Y,强度

python - Tensorflow:__new__() 在对象检测 API 中得到了一个意外的关键字参数 'serialized_options'

flask - 为什么 Flask WTForms 和 WTForms-SQLAlchemy QuerySelectField 会产生太多的值而无法解包?

python - 如何在 PasteDeploy ini 文件中包含第三方记录器格式化程序?