zoukankan      html  css  js  c++  java
  • 133-使用django实现评论数统计功能

    ***评论,点赞,收藏的功能,见我的119、135、136两篇文章***

    评论:https://www.cnblogs.com/lzhshn/p/13488142.html

    点赞:https://www.cnblogs.com/lzhshn/p/13624039.html

    收藏:https://www.cnblogs.com/lzhshn/p/13626118.html

    网上有一个方法(被转载了很多地方),是通过文章关联到评论,然后给评论进行计数。

    这种方法不是不行,但是我觉得有点复杂。我的思路是,给文章增加一个属性:评论数,当添加评论(或删除评论时),使用+=1,或-=1,然后save()一下即可。

    话不多说,看代码:

    【1】models部分,comment_num表示评论数,默认为0

    # Create your models here.
    class MyNote(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        author = models.CharField(max_length=64)
        title = models.CharField(max_length=64, default='a default title')
        content = RichTextField(config_name='awesome_ckeditor')
        pub_time = models.DateTimeField(auto_now_add=True)
        pub_date = models.DateField(auto_now_add=True)
        update_time = models.DateTimeField(auto_now=True)
        open_bool = models.BooleanField(default=True)
        comment_num = models.IntegerField(default=0)
        personal_tags = TaggableManager()
    
        def __str__(self):
            return self.title[0:32]
    

      

    【2】views部分,在添加评论的地方,修改comment_num的值,并保存。

    # 显示一篇文章,并可以添加评论
    # 为了避免直接在url里改编号,显示其他内容,还必须加上用户判断
    @login_required
    def one_note(request, pk):
        current_user = request.user
        pk_note = get_object_or_404(MyNote, author=current_user, id=pk)
        if request.method != 'POST':
            date_and_tag(request)
            comment_form = CommentForm()
            # pk_note = MyNote.objects.get(id=pk)
    
            # 可以不用在这里用_ser.all()的方式预先得到all_comment,减少上下文传入的内容
            # 而是直接到模板里通过for comment in pk_note.comment_set.all获得,注意模板里没有()
            all_comment = pk_note.comment_set.all().order_by('-add_time')
    
            context = {'pk_note': pk_note, 'date_index': list(set(date_list)),
                       'tag_index': list(set(tag_list)), 'all_comment': all_comment, 'comment_form': comment_form}
            return render(request, 'one_note.html', context)
    
        else:
            form = CommentForm(request.POST)
            if form.is_valid():
                new_comment = form.save(commit=False)
                new_comment.relation_note = pk_note
                new_comment.save()
                pk_note.comment_num += 1
                pk_note.save()
    
                return HttpResponseRedirect(reverse('notebook:one_note', args=[pk]))
    

      

    当系统收到所添加评论后,为其建立绑定对象,然后保存这个评论,再将绑定对象的评论数+1,然后保存这个绑定对象。即:pk_note.comment_num += 1和pk_note.save()。

    这种做法和count计数的方法各有优劣。

  • 相关阅读:
    Cesium加载Geowebcache切片
    Vue开发--脚手架的搭建
    OpenLayers动态测量距离和面积,并可自定义测量的线样式
    OpenLayers要素拖拽
    改造SuperMap的DrawHandler接口,自定义绘制的图形样式
    Cesium动态绘制实体(点、标注、面、线、圆、矩形)
    ArcMap制图遇到的小问题
    GeoServer 2.15.2版本跨域问题解决方法
    MySQL 8.0 主从同步
    Service__cmd--MySQL安装并连接SQLyog
  • 原文地址:https://www.cnblogs.com/lzhshn/p/13585889.html
Copyright © 2011-2022 走看看