如何在django-rest-framework中创建“ view_count”?

时间:2019-05-20 21:37:23

标签: django reactjs django-rest-framework

一直感谢您。我会问。 (对不起,英语不好)

我使用react作为前端,所以我刚刚启动了Django rest框架。

但是django-rest-framework对我来说很混乱,所以我问。

作为一个简单的例子,我想在单击Crud中的show page时自动增加view_count。

我应该在app_name / api / views.py中编写什么函数?

这是我的代码..

# notice/models.py

from django.db import models

# Create your models here.
class Notice(models.Model):
  title = models.CharField(max_length=120)
  description = models.TextField()
  view_count = models.IntegerField(default=0)

  def __str__(self):
    return self.title
# notice/api/views.py

from rest_framework import viewsets
from notice.models import Notice
from .serializers import NoticeSerializer
from django.http import JsonResponse

class NoticeViewSet(viewsets.ModelViewSet):
  serializer_class = NoticeSerializer
  queryset = Notice.objects.order_by('title')
# notice/api/serializers.py

from rest_framework import serializers
from notice.models import Notice

class NoticeSerializer(serializers.ModelSerializer):
  class Meta:
    model = Notice
    fields = ('id','title','description','view_count')

1 个答案:

答案 0 :(得分:1)

您将在NoticeViewSet.retrieve()方法中添加增量。这是检索单个对象时调用的view方法,因此很有意义。您也可以将其添加到list视图方法中,但是根据查询集的大小,它可能变得很慢。

class NoticeViewSet(viewsets.ModelViewSet):
    serializer_class = NoticeSerializer
    queryset=Notice.objects.order_by('title')

    def retrieve(self, request, *args, **kwargs):
        obj = self.get_object()
        obj.view_count = obj.view_count + 1
        obj.save(update_fields=("view_count", ))
        return super().retrieve(request, *args, **kwargs)

如果您还希望在列出“通知”时统计观看次数,请使用此类:

class NoticeViewSet(viewsets.ModelViewSet):
    serializer_class = NoticeSerializer
    queryset=Notice.objects.order_by('title')

    def retrieve(self, request, *args, **kwargs):
        obj = self.get_object()
        obj.view_count = obj.view_count + 1
        obj.save(update_fields=("view_count", ))
        return super().retrieve(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        # You could also increment the view count if people see the `Notice` in a listing.
        queryset = self.filter_queryset(self.get_queryset())
        for obj in queryset:
            obj.view_count = obj.view_count + 1
            obj.save(update_fields=("view_count", ))
        return super().list(request, *args, **kwargs