问题
I'm using Flask-SQLAlchemy version 2.1 which installs sqlalchemy version 1.x.
My below code which first fetch an array of resultset and then loop over to modify an existing attribute used to work but now it does not.
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..."
I get following error: attributeError: can't set attribute with 'topic_name'
回答1:
I had the same error ("AttributeError: can't set attribute" error) on a new column. It was due to a @property that I had previously added and that had the same name than the column.
回答2:
I have exactly the same error, i try to modify an sqlalchemy object that get from my db. When i print it i see a tuple, check if it is not. I solve the problem by refactoring my model, i want to add some field on my relation. First i have :
assoc_host_software = Table("host_software", Base.metadata,
Column("host_id", Integer, ForeignKey("host.id")),
Column("software_id", Integer, ForeignKey("software.id")),
)
then i try
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)
)
when i get the object from assoc_host_software and try to update him i get the same error as you get. I understand (and remember) that is not the right way to modify an object from relation many to many so i convert my model to
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")
i hope that will help
来源:https://stackoverflow.com/questions/37519428/attributeerror-cant-set-attribute-with-flask-sqlalchemy