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(db.Text)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
disabled = db.Column(db.Boolean)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
@staticmethod
def on_changed_body(target, value, oldvalue, initiator):
allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i',
'strong']
target.body_html = bleach.linkify(bleach.clean(
markdown(value, output_format='html'),
tags=allowed_tags, strip=True))
db.event.listen(Comment.body, 'set', Comment.on_changed_body)
The attributes of the Comment model are almost the same as those of Post. One addition
is the disabled field, a Boolean that will be used by moderators to suppress comments
that are inappropriate or offensive. As was done for blog posts, comments define an
event that triggers any time the body field changes, automating the rendering of the
Markdown text to HTML. The process is identical to what was done for blog posts in
Chapter 11, but since comments tend to be short, the list of HTML tags that are allowed
in the conversion from Markdown is more restrictive, the paragraph-related tags have
been removed, and only the character formatting tags are left.
To complete the database changes, the User and Post models must define the one-to-
many relationships with the comments table, as shown in Example 13-2.
Example 13-2. app/models/user.py: One-to-many relationships from users and posts to
comments
class User(db.Model):
# ...
comments = db.relationship('Comment', backref='author', lazy='dynamic')
class Post(db.Model):
# ...
comments = db.relationship('Comment', backref='post', lazy='dynamic')
166 | Chapter 13: User Comments