python - 请问我这样设计django文章的二级评论是否合理?

查看:125
本文介绍了python - 请问我这样设计django文章的二级评论是否合理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

没有过开发经验的新手,拜托各位大神指点一下,我应该怎么改进下面我下面这种二级评论的设计?如果描述的不够详细,我再补充。

ps: 我的思路,就是一篇文章和一级评论形成一对多的关系,然后一级评论和二级评论又形成一对多的关系。


models.py

class BlogComment(models.Model):
    """这是一级评论"""

    user_name = models.CharField('Name', max_length=100)  # 指定用户名
    body = models.TextField('Content')  # 评论的主体
    # 将一级评论关联对应的文章
    article = models.ForeignKey('Article', verbose_name='Article',
                                on_delete=models.CASCADE)

class SubComment(BlogComment):
    """这是二级评论,继承自一级评论,但是增加了一个parent_comment属性"""

    # 将二级评论关联对应的一级评论
    parent_comment = models.ForeignKey('BlogComment', verbose_name='BlogComment',
                                       on_delete=models.CASCADE)


froms.py中指定评论的表单

class BlogCommentForm(forms.ModelForm):
    """一级评论的表单"""
    class Meta:
        model = BlogComment  # 指定一级评论的model

        fields = ['user_name', 'body']

        widgets = {
            'user_name': forms.TextInput(attrs={
                'required': 'required',
            }),
            'body': forms.Textarea(attrs={
                'required': 'required',
            }),
        }

class SubCommentForm(BlogCommentForm):
    """二级评论的表单,继承自一级评论的表单"""
    class Meta:
        model = SubComment  # 制定二级评论的model

        fields = copy.deepcopy(BlogCommentForm.Meta.fields)

        widgets = copy.deepcopy(BlogCommentForm.Meta.widgets)


views.py

class CommentPostView(FormView):
    """一级评论视图层"""
    form_class = BlogCommentForm
    template_name = 'blog/article.html'

    def form_valid(self, form):
        # 保存表单到数据库
        comment = form.save(commit=False)
        comment.save()
        
        return HttpResponseRedirect('/')

    def form_invalid(self, form):
        # ... 一些提示用户表单输入不合理的信息

class SubCommentView(CommentPostView):
    """二级评论视图层,继承与一级评论视图层"""
    # 覆盖form_class成二级评论的表单
    form_class = SubCommentForm 

解决方案

可以这样设计,没有问题,至于更深层级的评论只需要在二级评论表内加上评论人和被评论人的字段进行识别即可。我博客的评论大体就是这样做的。具体效果可以参考:https://www.rapospectre.com/b...。具体实现:https://github.com/bluedazzle...

这篇关于python - 请问我这样设计django文章的二级评论是否合理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆