AttributeError: 'InstrumentedList'对象没有该属性
我有这些表格:
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
当我尝试运行这个代码时,在“如果值为真”的条件下,我收到了这个错误代码:
AttributeError: 'InstrumentedList' object has no attribute 'upvotes'
我试过给Voteinfo一个独特的ID,并在关系中加上uselist=False。我还试过把关系从VoteThing换成Voteinfo,但都没有解决问题。我不知道什么是InstrumentedList。这到底是怎么回事?
3 个回答
0
真是不可思议,事情变化得太快了,不过这个帮了我很多!我在使用 lazy = 'dynamic' 时遇到了一个错误,但我的代码是这样的:
tool = db.relationship("Tool", backref="activities", uselist=False)
这段代码给了我 db.model 类型,这正是我想要的,而不是一个被仪器化的类列表类型。
0
在这里,可能会有用的是给请求添加一个参数 lazy='dynamic',这样查询就不会自动执行了,也不会自动刷新(thing = relationship('Thing', backref='voteinfo', lazy='dynamic')
)。如果不这样做,系统内部会自动调用 all() 来返回 'thing' 的列表,这样就会出现一个错误:AttributeError: 'InstrumentedList' 对象没有这个属性!
32
在文档中有解释,链接在这里: https://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-one。你需要把 uselist=False 这个设置加到 backref 上,而不是关系本身。
thing = relationship('Thing', backref=backref('voteinfo', uselist=False))