Django hit计算基于类的视图

时间:2013-04-17 23:30:36

标签: python django count classview

我正在尝试做像youtube观看的内容:

models.py
class Video(models.Model):
    title = models.CharField(max_length=100)
    embed = models.TextField
    created_at = models.DateTimeField(auto_now_add=True,editable=False)
    updated_at = models.DateTimeField(auto_add=True,editable=False)
    visit_count = models.IntegerField(default=0)

    def add_visit(self):
        if self.visit_count is not None:
            self.visit_count += 1
        else:
            self.visit_count = 0

views.py
class VideoDetail(DetailView):
    model = Video

    def get_context_data(self, **kwargs):
        context = super(VideoDetail, self).get_context_data(**kwargs)
        self.object.add_visit()
        self.object.save()
        return context

Example use:
    Video.objects.order_by('-visit_count')

一切正常,但并不完全,因为我可以通过IP计算限制。

class Video(models.Model):
    title = models.CharField(max_length=100)
    embed = models.TextField
    created_at = models.DateTimeField(auto_now_add=True,editable=False)
    updated_at = models.DateTimeField(auto_add=True,editable=False)

class Visit(models.Model):
    video = models.ForeignKey(Video)
    ip = models.IPAddressField()
    visit_count = models.IntegerField(default=0)

如何在视图或模型中插入:visit_count,ip,video。

3 个答案:

答案 0 :(得分:0)

在视图中:

def get(self, req, *k, **kw)
   is_created, visit = Visit.objects.get_or_create(this.object, ip)
   if is_created:
      this.object.add(visit)
   else: 
      visit.count +=1
      visit.save()

答案 1 :(得分:0)

我将使用IP地址扩展您的add_visit()模型方法:

def add_visit(self, ip):
    _, visit = Visit.objects.get_or_create(self, ip)
    visit.count += 1

并按原样使用您的DetailView。

答案 2 :(得分:0)

您可以使用 get_object 是检索对象的方法

from django.utils import timezone
from django.views.generic import DetailView
from books.models import Author

class AuthorDetailView(DetailView):

    queryset = Author.objects.all()

    def get_object(self):
        obj = super().get_object()
        # Record the last accessed date
        obj.last_accessed = timezone.now()
        obj.save()
        return obj

来源:https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/