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