適應於網頁、文章等瀏覽次數統計ide
一、Models設置:添加viewed方法spa
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'])
二、views設置:查詢成功後調用viewed方法code
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)