这里我想在每次调用详细视图时将视图的数量增加1。我该怎么做?
class Package(models.Model):
name = models.CharField(max_length=255,unique=True)
slug = AutoSlugField(populate_from='name')
package_desc = models.TextField()
views = models.IntegerField(default=0) #want to increase views by 1 when detail_package url hits
views.py
class DetailPackage(generics.RetrieveAPIView):
serializer_class = PackageDetailSerializer
lookup_field = 'slug'
queryset = Package.objects.all()
urls.py
path('<slug>/detail/', DetailPackage.as_view(), name='detail_package'),
我是django rest框架的新手。那么,对于这种情况,我使用泛型API视图是不是走对了路?
您可以重写(generics.RetrieveAPIView(上的检索方法http://www.cdrf.co/3.9/rest_framework.generics/RetrieveAPIView.html#retrieve
下面是一个示例
from django.db.models import F
class DetailPackage(generics.RetrieveAPIView):
...
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
# increment the value
type(instance).objects.filter(pk=instance.pk).update(
views=F('views') + 1,
)
return Response(serializer.data)
正如@Aprimus所建议的,我通过重写retrieve((方法来解决这个问题,如下所示:
如果我做得不对,请纠正我。
class DetailPackage(generics.RetrieveAPIView):
serializer_class = PackageDetailSerializer
lookup_field = 'slug'
queryset = Package.objects.all()
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
instance.views += 1
instance.save()
serializer = self.get_serializer(instance)
return Response(serializer.data)