def get_valid_comment_by_id_and_article(id, a_id): try: return Comment.objects.get( id=id, article_id=a_id, status__in=CommentStatusChoices.valid_choices()) except: return None
class Comment(models.Model): """ 以下说的 评论、回复 其实是一个东西,方便区分用了两个词 评论:对文章的评论称作 "评论"; 回复:对评论的评论称作 "回复",对回复的回复也叫 "回复"; """ class Meta: verbose_name = '评论' verbose_name_plural = '评论' nickname = models.CharField(verbose_name='昵称', max_length=20, null=True, blank=True) email = models.EmailField(verbose_name='邮箱', null=True, blank=True) content = models.TextField(verbose_name='内容') article_id = models.IntegerField(verbose_name='article_id') status = models.IntegerField(verbose_name='状态', choices=CommentStatusChoices.to_django_choices(), default=CommentStatusChoices.Created) """ 注意区分root_id和to_id, 评论 root_id必须是-1 对评论的回复 root_id==to_id 如: 文章-0 |__ 评论-1 |__ 回复-2 |__ 回复-3 |__ 回复-3-1 评论-1 :root_id是 -1; to_id是 -1 回复-2 :root_id是 评论-1 的id; to_id是 评论-1 的id; 回复-3 :root_id是 评论-1 的id; to_id是 评论-1 的id; 回复-3-1 :root_id是 评论-1 的id; to_id是 回复-3 的id; """ # 根id,评论的root_id就是article_id,回复的root_id就是 评论id root_id = models.IntegerField(verbose_name='root_id') # 对评论的回复, to_id是-1 # 对回复的回复,to_id是回复的id to_id = models.IntegerField(verbose_name='to_id', default=-1) type = models.IntegerField(verbose_name='type', choices=Comment_Type) created_time = models.DateTimeField(verbose_name="创建时间", default=timezone.now, editable=False) modified_time = models.DateTimeField(verbose_name="修改时间", auto_now=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.nickname = clean_all_tags(self.nickname) if self.email: self.email = clean_all_tags(self.email) self.content = get_safe_comment_html(self.content) super().save(force_insert, force_update, using, update_fields) def article(self): from app.db_manager.content_manager import get_article_by_id return get_article_by_id(self.article_id) def url(self): return reverse('app:detail_article', args=(self.article_id,)) + '#comment-' + str(self.id) def get_absolute_url(self): return self.url() def __str__(self): return '评论<%s>' % self.id
def filter_valid_comment_by_article(a_id): return Comment.objects.filter(article_id=a_id, status__in=CommentStatusChoices.valid_choices())