Vivek Singh Bisht
Vivek Singh Bisht

Reputation: 67

Returning data to the client from database containing relational tables

I'm developing a blogging system using Angular(Front-end) and Flask(Back-end). The database used for this application is sqlite.

I have a blog and a tags table which follow many-to-many relationship:

class Blog(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    authorname=db.Column(db.String(128),nullable=False)
    title=db.Column(db.String(128),nullable=False)
    content=db.Column(db.Text,nullable=False)
    user_id=db.Column(db.Integer,db.ForeignKey('user.id'))
    tags= db.relationship('Tag',secondary=tags_blog,backref=db.backref('blogs_associated',lazy="dynamic"))
    featured_image= db.Column(db.String,nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow)
    upvotes= db.Column(db.Integer, default=0)
class Tag(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(100))

tags_blog = db.Table('tags_blog',
    db.Column('blog_id', db.Integer,db.ForeignKey('blog.id')),
    db.Column('tag_id',db.Integer,db.ForeignKey('tag.id'))
)  

I have a route in the back-end which queries and returns the blog of specific id,

@blogs.route('/blog/<int:id>', methods=["GET"])
def show_blog(id):
    blog_by_id= Blog.query.filter_by(id=id).first_or_404()

    found_blog ={
        "id": blog_by_id.id,
        "title":blog_by_id.title,
        "content":blog_by_id.content,
        "authorname":blog_by_id.authorname,
        "featured_image":blog_by_id.featured_image,
        "tags":[]
    }


    return jsonify({"blog": found_blog})

As you can see in the route,the tags property inside found_blog is empty since, when I try to add blog_by_id.tags to the tags property I get an error saying Object of type Tag is not JSON serializable.

I tried the following code but got the same error:

for x in blog_by_id.tags:
  found_blog["tags"].append(x)

How do I access the tags related to each blog so that I can return the complete blog details to the client-side?

Upvotes: 0

Views: 31

Answers (1)

aman kumar
aman kumar

Reputation: 3156

you can try below code

class Blog(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    authorname=db.Column(db.String(128),nullable=False)
    title=db.Column(db.String(128),nullable=False)
    content=db.Column(db.Text,nullable=False)
    user_id=db.Column(db.Integer,db.ForeignKey('user.id'))
    tags= db.relationship('Tag',secondary=tags_blog,backref=db.backref('blogs_associated',lazy="dynamic"))
    featured_image= db.Column(db.String,nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow)
    upvotes= db.Column(db.Integer, default=0)

   @property
   def serialize(self):
      return {
       'id': self.id,
        'authorname': self.authorname,
       'title': self.title,
       'content': self.content,
       'user_id': self.user_id,
       'featured_image': self.featured_image,
       'updated_at': self.updated_at,
       'upvotes': self.upvotes
      }

class Tag(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(100))

   @property
   def serialize(self):
      return {
       'id': self.id,
       'name': self.name     
     }


import josn

@blogs.route('/blog/<int:id>', methods=["GET"])
def show_blog(id):
    blog= Blog.query.filter_by(id=id).first_or_404()
    data = blog.serialize
    data['tags'] = []
    for tag in blog.tags.all():
        data['tags'].append(tag.serialize)   
    return jsonify(data)

Upvotes: 1

Related Questions