1

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?

  • using a comment because im not able to debug it at the moment, but in general that exception means the json module was asked to serialize an object other than a string, int or other basic json datatypes. The json encoder needs to be passed a handler function so it knows how to represent the object as one of them. Here's a good example of how to write the handler, but im not sure where json is getting called that your app is breaking http://stackoverflow.com/a/15823348/5425358 – tlastowka Oct 10 '15 at 20:13

1 Answers1

1

Python's json module doesn't try to figure out how to serialize arbitrary objects. It only knows about the Python types that have an equivalent JSON type: dict, list, str, int, float, bool, None. You need to instruct it how to dump other types. SQLAlchemy models can be particularly complex: there are many column types that don't have an equivalent JSON type, do you embed relationships or just include their foreign keys, what about hybrid properties, etc. Rather than trying to make decisions for you, Python requires you to tell it how to reduce a complex object to the basic types.

davidism
  • 121,510
  • 29
  • 395
  • 339