[PYTHON] How to convert a class object to a dictionary with SQLAlchemy

Overview

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}>'

Method 1 (access __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'}

Method 2 (Prepare a function that returns a dict type on the class side)

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
		}

For the search

** 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

How to convert a class object to a dictionary with SQLAlchemy
How to convert an array to a dictionary with Python [Application]
How to make a dictionary with a hierarchical structure.
How to update with SQLAlchemy?
How to Alter with SQLAlchemy?
How to Delete with SQLAlchemy?
How to convert / restore a string with [] in python
How to write a Python class
How to INNER JOIN with SQLAlchemy
How to add a package with PyCharm
[Python] How to make a class iterable
[Python] How to convert a 2D list to a 1D list
How to use SQLAlchemy / Connect with aiomysql
How to access data with object ['key'] for your own Python class
How to read a CSV file with Python 2/3
How to send a message to LINE with curl
How to draw a 2-axis graph with pyplot
How to create a function object from a string
How to generate a Python object from JSON
Save the object to a file with pickle
How to create a multi-platform app with kivy
How to convert (32,32,3) to 4D tensor (1,32,32,1) with ndarray type
How to use dictionary {}
How to apply updlock, rowlock, etc. with a combination of SQLAlchemy and SQLServer
[Tentative] How to convert a character string to Shift_jis with kivy-ios Memo kivy v1.8.0
[Python] How to draw a line graph with Matplotlib
How to create a submenu with the [Blender] plugin
Convert a text file with hexadecimal values to a binary file
How to get a logged-in user with Django's forms.py
How to convert horizontally held data to vertically held data with pandas
How to make a shooting game with toio (Part 1)
How to write a list / dictionary type of Python3
How to export / import Zope zope object installed with Plone-4.1.5-UnifiedInstaller-20120604.tgz
How to get more than 1000 data with SQLAlchemy + MySQLdb
How to convert JSON file to CSV file with Python Pandas
How to convert a mel spectrogram back to a wav file
Convert / return class object to JSON format in Python
[Morphological analysis] How to add a new dictionary to Mecab
[Python] How to create a 2D histogram with Matplotlib
[Python] How to draw a scatter plot with Matplotlib
How to use python multiprocessing (continued 3) apply_async in class with Pool as a member
How to call a function
Introduction to RDB with sqlalchemy Ⅰ
How to cast with Theano
How to hack a terminal
How to separate strings with','
How to RDP with Fedora31
How to deploy a web app made with Flask to Heroku
How to output a document in pdf format with Sphinx
How to use the __call__ method in a Python class
[Python] How to play with class variables with decorator and metaclass
How to create a flow mesh around a cylinder with snappyHexMesh
How to print characters as a table with Python's print function
How to make a simple Flappy Bird game with pygame
I tried to get started with Hy ・ Define a class
How to display a list of installable versions with pyenv
How to extract other than a specific index with Numpy
A story about how to deal with the CORS problem
How to build a python2.7 series development environment with Vagrant
Convert Tweepy Status object to JSON
How to set a shortcut to switch full-width and half-width with IBus