Attempting to treat a SQLAlchemy row object the same as a dictionary type does not work because the types are different. There are several patterns, but I will introduce two methods.
It is easier to understand if there is a concrete example, so I will explain it based on the Todo class below as a sample.
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column( db.Integer, primary_key=True )
description = db.Column( db.String(), nullable=False )
completed = db.Column( db.Boolean, nullable=False, default=False )
def __repr__(self):
return f'<Todo {self.id} {self.description}>'
__dict__
)You can get the dictionary type value by accessing the __dict__
property.
However, please note that this method also gets the property _sa_instance_state
.
todo = Todo.query.first()
print( todo.__dict__ )
# {'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x10f4559e8>, 'completed': False, 'id': 17, 'description': 'TASK1'}
You can also get the dictionary type value by preparing a function that returns the dictionary type value on the class side.
todo = Todo.query.first()
print( todo.toDict() )
# {'id': 17, 'description': 'TASK1', 'completed': False}
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column( db.Integer, primary_key=True )
description = db.Column( db.String(), nullable=False )
completed = db.Column( db.Boolean, nullable=False, default=False )
list_id = db.Column( db.Integer, db.ForeignKey('todolists.id'), nullable=False )
def __repr__(self):
return f'<Todo {self.id} {self.description}>'
def toDict(self):
return {
'id': self.id,
'description': self.description,
'completed': self.completed
}
** 1. Error when trying to add a property to a row object **
todo = Todo.query.first()
todo['label'] = 'Important'
# TypeError: 'Todo' object does not support item assignment
** 2. Error when trying to convert using the dict () function **
todo = Todo.query.first()
dict(todo)
# TypeError: 'Todo' object is not iterable
Recommended Posts