Django DetailView 计数增加 3 而不是 1
Django DetailView count increases by 3 instead of 1
我有一个网页,每个浏览量都按 3 计算并递增,而本应递增 1
这是我 views.py
中的内容
from django.views.generic import ListView, DetailView
class MovieDetail(DetailView):
model = Movie
def get_object(self):
object = super(MovieDetail, self).get_object()
object.views_count += 1
object.save()
return object
def get_context_data(self, **kwargs):
context = super(MovieDetail, self).get_context_data(**kwargs)
context['links'] = MovieLink.objects.filter(movie=self.get_object())
context['related_movies'] = Movie.objects.filter(category=self.get_object().category)
return context
html
<section class="movie">
<img src="{{object.image.url}}">
<ul>
<li>{{object}}</li>
<li>{{object.description}}</li>
<li><a href="genre.html">Adventure</a>, <a href="genre.html">Drama</a>, <a href="genre.html">Romance</a></li>
<li><a href="">{{object.cast}}</a></li>
<li><i class="fa fa-eye" id="eye"></i> {{object.views_count}}</li>
</ul>
</section>
计划递增 1 但不遵循该逻辑..这里出了什么问题?
get_object()
在处理您的视图时可能会被多次调用。
例如,您可以将代码移动到 render_to_response()
方法。还要确保使用 F() expressions.
增加数据库字段
from django.db.models import F
class MovieDetail(DetailView):
model = Movie
def render_to_response(self, *args, **kwargs):
self.object.views_count = F('views_count') + 1
self.object.save()
return super().render_to_response(*args, **kwargs)
我有一个网页,每个浏览量都按 3 计算并递增,而本应递增 1
这是我 views.py
中的内容from django.views.generic import ListView, DetailView
class MovieDetail(DetailView):
model = Movie
def get_object(self):
object = super(MovieDetail, self).get_object()
object.views_count += 1
object.save()
return object
def get_context_data(self, **kwargs):
context = super(MovieDetail, self).get_context_data(**kwargs)
context['links'] = MovieLink.objects.filter(movie=self.get_object())
context['related_movies'] = Movie.objects.filter(category=self.get_object().category)
return context
html
<section class="movie">
<img src="{{object.image.url}}">
<ul>
<li>{{object}}</li>
<li>{{object.description}}</li>
<li><a href="genre.html">Adventure</a>, <a href="genre.html">Drama</a>, <a href="genre.html">Romance</a></li>
<li><a href="">{{object.cast}}</a></li>
<li><i class="fa fa-eye" id="eye"></i> {{object.views_count}}</li>
</ul>
</section>
计划递增 1 但不遵循该逻辑..这里出了什么问题?
get_object()
在处理您的视图时可能会被多次调用。
例如,您可以将代码移动到 render_to_response()
方法。还要确保使用 F() expressions.
from django.db.models import F
class MovieDetail(DetailView):
model = Movie
def render_to_response(self, *args, **kwargs):
self.object.views_count = F('views_count') + 1
self.object.save()
return super().render_to_response(*args, **kwargs)