gpt4 book ai didi

django - 我如何在 django-rest-framework 中制作 'view_count'?

转载 作者:行者123 更新时间:2023-12-04 01:43:43 26 4
gpt4 key购买 nike

谢谢你一直以来。我会问。(我很抱歉英语不太好)

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

但是 django-rest-framework 让我感到困惑,所以我问。

作为一个简单的例子,当我点击 crud 中的显示页面时,我想自动增加 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')

最佳答案

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

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

关于django - 我如何在 django-rest-framework 中制作 'view_count'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com