avinoth
avinoth

Reputation: 430

Flask use SQL query at client side

I am doing a small project in Python / Flask.. My database model consists of two tables say post and comments.. Post table consists of the posts and the comments table consists of the comments for the post. Post and comment are linked..

I have two templates in place, feed.html and blogpost.html.. In feed.html a list of title of post's will be shown and when clicked through the title link it will show the full post content via blogpost.html..

Now, in the feed.html it will list all the posts which is fine now.. But I want to implement the number of comments each post has, which can be easily queried from the server end but the issue is - I am passing all the posts to the feed.html and rendering each post title using for loop in the client side..

user = User.query.filter_by(name = name).first()
return render_template("feed.html",
posts = Post.query.filter_by(user_id = user.id).order_by(Post.timestamp.desc()).all())

and at the feed.html, I am rendering as,

{ % for post in posts %}
     <a href="/feed/{{post.id}}" class="post-title">{{ post.title }}</a>
      by <a href="/feed/{{ post.author.name }}">{{ post.author.name }}</a> 
      | {{ post.timestamp}} 
      | <a href="#"> TROUBLESOME PART </a> 
{% endfor %}

I am currently stuck here..

I can get the number of comments a post has by executing,

comments = Comment.query.filter_by(post_id = post.id).all()
len(comments)

but I have no way of doing that query for individual posts when on the whole it is passed through the template..

Kindly help on this...

Upvotes: 0

Views: 323

Answers (1)

davidism
davidism

Reputation: 127210

Set up a many-to-one two-way relationship between Comment and Post:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)


class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True
    post_id = db.Column(db.Integer, db.ForeignKey(Post.id), nullable=False)

    post = db.relationship(Post, backref='comments')

Now if you have an instance of Post, you can do post.comments to get the comments for that post. In a Jinja template, use post.comments|length to get the count.

Upvotes: 2

Related Questions