Reputation: 633
I am using flask_marshmallow (0.10.1) to serialize the data from my flask_sqlalchemy tables into JSON objects.
However there is a relationship between the 2 tables (Post and Comments). I've done some research but I'm not sure how to use nesting or what to call to properly serialize into JSON.
Here are my flask_sqlalchemy classes:
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
comments = db.relationship('Comment',backref='post_owner') #This needs an integer to increment im
def __repr__(self):
return f"Post({self.id}, {self.content}), {self.comments}"
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
comment = db.Column(db.Text, nullable=True)
owner_id = db.Column(db.Integer, db.ForeignKey('post.id'))
def __repr__(self):
return f"Comment {self.comment}"
Then here are my flask_marshmallow schemas:
class PostSchema(ma.ModelSchema):
class Meta:
model = Post
class CommentSchema(ma.ModelSchema):
class Meta:
model = Comment
Lastly here is the function where I'm calling the schema to serialize:
def convert_to_json(post_to_convert):
post_schema = PostSchema()
output = post_schema.dump(post_to_convert)
return output
The current output I get is this:
{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) [1, 2, 3]
What I WANT to get (in comments:) is this:
{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) ["first comment", "second comment", "third comment"]
I need the actual comment text data not just the Id numbers which is what I'm getting. Any help is appreciated thanks.
Upvotes: 1
Views: 2181
Reputation: 3608
You can easily achieve that with a Nested
field in your PostSchema
(assuming you are using marshmallow-sqlalchemy
) :
from marshmallow_sqlalchemy.fields import Nested
class PostSchema(ma.ModelSchema):
class Meta:
model = Post
comments = Nested(CommentSchema, many=True)
class CommentSchema(ma.ModelSchema):
class Meta:
model = Comment
I recommend you read Marshmallow's documentation about Nesting schemas to understand the different options and arguments. Also, the documentation of Marshmallow SQLAlchemy, particularly the "Recipes" section is helpful and give ideas on how to build schemas.
Upvotes: 2