I have the following Flask-SQLAlchemy model in a declarative base
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
pw = db.Column(db.String(20), unique=False)
last_login = db.Column(db.DATETIME)
posts = db.relationship('Post', backref='User')
def __init__(self, i, u, p):
self.id = i
self.username = u
self.pw = p
def __repr__(self) -> str:
return '<User %s, id = %d>' % (self.username, self.id)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
rest_text = db.Column(db.Text)
date = db.Column(db.DateTime)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __init__(self, title: str, rest: str, author: User):
self.author = author
self.title = title
self.rest_text = rest
self.date = datetime.now()
self.id = randint(0, MAX_POSTS_NUM)
while self.id in db.session.query(Post.id).all():
self.id = randint(0, MAX_POSTS_NUM)
where db
is an instance of SQLAlchemy(app)
object imported from the __init__
file of my Flask applicaiton. I have an already existing sqlite3 database with a single user, named 'test', and when I do a query in Flask using
u = User.query.filter_by(username='test').first()
u.username
I get the following error
TypeError: <User test, id = 1> is not JSON serializable
The question si why this is not JSON serializable
. What makes a class/model JSON serializable
?