针对每条博客的观看次数我么是使用django的Mixin实现的:
def get(self, request, *args, **kwargs): last_visit = request.session.get(‘last_visit‘) reset_last_visit_time = False if last_visit: last_visit_time = datetime.datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S") if (datetime.datetime.utcnow() - last_visit_time).seconds > 0: obj = super(ArticleDetailView, self).get_object() obj.views = obj.views + 1 obj.save() reset_last_visit_time = True else: reset_last_visit_time = True if reset_last_visit_time: request.session[‘last_visit‘] = str(datetime.datetime.utcnow()) return super(ArticleDetailView, self).get(request, *args, **kwargs)
而根据日期归档则比较麻烦,借鉴了Mysql必知必会得到了思路代码如下:
class DateView(ListView): template_name = ‘apps/full-width.html‘ context_object_name = ‘article_list‘ paginate_by = 10 def get_queryset(self): year = self.kwargs[‘year‘] month = self.kwargs[‘month‘] start_date = datetime.date(int(year), int(month), 1) end_date = datetime.date(int(year), int(month), 31) article_list = Article.objects.filter(create_time__range=(start_date, end_date)) return article_list
时间: 2024-10-07 13:35:33