「Django」浏览+1的操作
适应于网页、文章等浏览次数统计
1、Models设置:添加viewed方法
class NewsTitle(models.Model): title = models.CharField(max_length=64,verbose_name='新闻标题') count = models.PositiveIntegerField(verbose_name='点击次数',default=0) src = models.ImageField(upload_to='www/',verbose_name='新闻图片') is_del = models.BooleanField(verbose_name='删除', default=False) time = models.DateTimeField(auto_now=True) class Meta: verbose_name = '新闻标题' verbose_name_plural = verbose_name def __str__(self): return self.title def viewed(self): self.count += 1 self.save(update_fields=['count'])
2、views设置:查询成功后调用viewed方法
def retrieve(self,request,*args,**kwargs): ret = {'code': 1000, 'data': None} pk = kwargs.get('pk') try: obj = models.NewsTitle.objects.filter(id=pk,is_del=False) obj.first().viewed() ser = sel.GetNewsInfoSerializers(instance=obj, many=True) ret['data'] = ser.data except Exception as e: ret['code'] = 1002 ret['err'] = e return Response(ret)