Tony
Tony

Reputation: 1140

Jsonify flask-sqlalchemy many-to-one relationship in flask

I was trying to make rest apis with flask-restful where i am using flask-sqlalchemy as the ORM.Here is my model classes.

class Post(db.Model):
__tablename__ = 'post'
postid = db.Column(db.Integer,primary_key=True)
post = db.Column(db.String(64))
userid = db.Column(db.Integer,db.ForeignKey('user.userid'))

#serialize property used for serializing this class to JSON
@property
def serialize(self):
    return {
        'postid': self.postid,
        'post': self.post,
        'author':self.author
    }

and

class User(db.Model):
userid = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(30))
email = db.Column(db.String(20))
posts = db.relationship('Post',backref="author",lazy='dynamic')

#serialize property used for serializing this class to JSON
@property
def serialize(self):
    return {
        'username': self.username,
        'email': self.email
    }

And the database is populated.now i am trying to make the json out of this

class PostList(Resource):
    def get(self):
        posts = DL_models.Post.query.all()
        posts = [post.serialize for post in posts]
        return { 'posts': posts }

api.add_resource(PostList, '/twitter/api/v1.0/posts', endpoint = 'posts')

This works perfect when i change serialize method in Post to

@property
def serialize(self):
    return {
        'postid': self.postid,
        'post': self.post,
        'author':self.postid
    }

This returns expected json output but when i am changing to 'author':self.author i am getting a error

TypeError: <app.DL_models.User object at 0x7f263f3adc10> is not JSON serializable

I understand that i have to call serialize on those nested objects as well but i could not figure out how to do it.

Or please share your experience to encode relationships in sqlalchemy.

Upvotes: 4

Views: 4250

Answers (2)

justanr
justanr

Reputation: 750

Since you're already using Flask-Restful, have you considered using their built in data marshaling solution?

However, for marshaling complex data structures, I find that Marshmallow does the task about a thousand times better, even making nesting serializers within others easy. There's also a Flask extension designed to inspect endpoints and output URLs.

Upvotes: 4

Liam
Liam

Reputation: 1171

This is a punt but have you tried the below?

'author': self.author.username

From the error message I'm guessing it's getting to User but doesn't know what you want from it.

Upvotes: 0

Related Questions