2

我正在尝试做类似 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。

4

3 回答 3

1

在视图中:

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()
于 2013-04-17T23:57:29.103 回答
0

我会add_visit()用 IP 地址扩展你的模型方法:

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

并按原样使用您的 DetailView。

于 2020-01-13T20:15:23.710 回答
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/

于 2020-10-03T05:33:07.227 回答