我有这些表格:
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/