属性错误:无法使用Flask-SQLAlchemy设置属性。

5

我正在使用Flask-SQLAlchemy版本2.1,它安装了SQLAlchemy版本1.x。

我的下面这段代码首先获取一个结果集数组,然后循环遍历以修改现有属性,但现在它不起作用了。

question_topic = Question.query.join(Topic).join(User,User.id==Question.user_id).add_columns(User.email,Question.question, Question.date, Topic.topic_name, Question.id, Topic.question_id)\
        .filter(Question.id == Topic.question_id).all()



for q_t in question_topic:
    q_t.topic_name = q_t.topic_name + "some text..."

我遇到了以下错误: 属性错误:无法使用'topic_name'设置属性。

如果我降级SQLalchemy到0.9,代码就可以正常工作。 - user1501382
http://docs.sqlalchemy.org/en/rel_1_0/changelog/changelog_10.html - hjpotter92
@hjpotter92 我已经阅读了发布说明,但无法找到确切的功能/错误,导致这种行为的出现,以及如何恢复旧有的行为。你能帮我一下吗? - user1501382
你的过滤表达式应该是 Topic 的连接。 - dirn
http://docs.sqlalchemy.org/en/rel_1_0/changelog/changelog_10.html#change-8dff32ea855329842148a57ea75d4663 - Ilja Everilä
2个回答

6

我在新列上遇到了同样的错误("AttributeError: can't set attribute" error)。这是因为我之前添加了一个与该列同名的 @property。


1

我有完全相同的错误,我尝试修改从数据库中获取的SQLAlchemy对象。当我打印它时,我看到一个元组,请检查它不是。我通过重构我的模型来解决问题,我想在我的关系中添加一些字段。首先我有:

assoc_host_software = Table("host_software", Base.metadata,
    Column("host_id", Integer, ForeignKey("host.id")),
    Column("software_id", Integer, ForeignKey("software.id")),
)

然后我尝试。
assoc_host_software = Table("host_software", Base.metadata,
    Column("host_id", Integer, ForeignKey("host.id")),
    Column("software_id", Integer, ForeignKey("software.id")),
    Column("in_date",DateTime, unique=False, nullable=True),
    Column("out_date",DateTime, unique=False, nullable=True)
)

当我从assoc_host_software获取对象并尝试更新它时,我得到了与你相同的错误。 我明白(并记得)这不是修改多对多关系对象的正确方式, 所以 我将我的模型转换为

class Host_Software(Base):
    """Model for relation host software."""
    __tablename__ = 'host_software'
    host_id = Column(Integer, ForeignKey("host.id"), primary_key=True)
    software_id = Column(Integer, ForeignKey("software.id"), primary_key=True)
    in_date = Column(DateTime, unique=False, nullable=True)
    out_date = Column(DateTime, unique=False, nullable=False)
    software = relationship("Software", backref="software_associations")
    host = relationship("Host", backref="host_associations")

我希望那能帮到你


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接