PCv5/app/models/comment.py

72 lines
2.0 KiB
Python
Raw Normal View History

2019-08-20 17:34:00 +02:00
from app import db
from app.models.post import Post
2022-05-26 21:08:01 +02:00
from app.models.attachment import Attachment
from sqlalchemy.orm import backref
2019-08-20 17:34:00 +02:00
2021-01-12 16:40:52 +01:00
2019-08-20 17:34:00 +02:00
class Comment(Post):
__tablename__ = 'comment'
__mapper_args__ = {'polymorphic_identity': __tablename__}
# ID of the underlying Post object
2019-08-20 17:34:00 +02:00
id = db.Column(db.Integer, db.ForeignKey('post.id'), primary_key=True)
# Comment contents
2019-08-20 17:34:00 +02:00
text = db.Column(db.UnicodeText)
# Parent thread
thread_id = db.Column(db.Integer, db.ForeignKey('thread.id'),
nullable=False, index=True)
thread = db.relationship('Thread',
backref=backref('comments', lazy='dynamic'),
foreign_keys=thread_id)
2022-05-12 21:45:00 +02:00
attachments = db.relationship('Attachment', back_populates='comment',
lazy='joined')
@property
def is_top_comment(self):
return self.id == self.thread.top_comment_id
2019-08-20 17:34:00 +02:00
def __init__(self, author, text, thread):
"""
Create a new Comment in a thread.
Arguments:
author -- comment poster (User)
text -- contents (unicode string)
thread -- parent discussion thread (Thread)
"""
Post.__init__(self, author)
self.thread = thread
self.text = text
def edit(self, new_text):
"""Edit a Comment's contents."""
self.text = new_text
self.touch()
def delete(self):
"""Recursively delete post and all associated contents."""
for a in self.attachments:
a.delete()
db.session.commit()
db.session.delete(self)
2022-05-26 21:08:01 +02:00
def create_attachments(self, multiple_file_field_data):
"""Create attachements from a form's MultipleFileField.data."""
attachments = []
for file in multiple_file_field_data:
if file.filename != "":
a = Attachment(file, self)
attachments.append((a, file))
db.session.add(a)
db.session.commit()
for a, file in attachments:
a.set_file(file)
def __repr__(self):
return f'<Comment: #{self.id}>'