O'Reilly logo

Flask Web Development, 2nd Edition by Miguel Grinberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13. User Comments

Allowing users to interact is key to the success of a social blogging platform. In this chapter, you will learn how to implement user comments. The techniques presented are generic enough to be directly applicable to a large number of socially enabled applications.

Database Representation of Comments

Comments are not very different from blog posts. Both have a body, an author, and a timestamp, and in this particular implementation both are written with Markdown syntax. Figure 13-1 shows a diagram of the comments table and its relationships with other tables in the database.

Database representation of blog post comments.
Figure 13-1. Database representation of blog post comments

Comments apply to specific blog posts, so a one-to-many relationship from the posts table is defined. This relationship can be used to obtain the list of comments associated with a particular blog post.

The comments table is also in a one-to-many relationship with the users table. This relationship gives access to all the comments made by a user, and indirectly how many comments a user has written, a piece of information that can be interesting to show in user profile pages. The definition of the Comment model is shown in Example 13-1.

Example 13-1. app/models.py: comment model
class Comment(db.Model):
    __tablename__ = 'comments'
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    body_html = db.Column ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required