模型问题有一个view_counts字段来计算一个问题的查看次数。
和thre是一个单击以绑定方法
def count_views(request, question_id):
question = Question.objects.get(pk=question_id)
if request.is_ajax():
question.views_count = question.views_count + 1
question.save()
else:
url = '/error/show_error/4'
return HttpResponseRedirect(url)
count = question.views_count
json = simplejson.dumps(count)
return HttpResponse(json, mimetype='application/json')
$('.question a').click(function () {
pk = $(this).attr('pk');
$.get("/question/count_views/" + pk, function(data) {
location.href='/question/show_question/' + pk;
});
});
<div class='question'>{{ forloop.counter }}. [{{ question.country }}] <a pk={{ question.pk }}>{{ question.question }}</a></div>
但是如果具有相同ip的客户端在5分钟内点击相同的问题,则views_count将不会增加
如何实现这个目标?
就像在stackoverflow中一样,你不能在5秒内编辑一条评论。
答案 0 :(得分:0)
带着我的建议,我对django和python很新,我没有测试过这个,但我会像这样实现这个:
创建新模型:
class LastViewed(models.Model):
ip = models.IPAddressField()
last_view = models.DateField()
question = models.ForeignKey(Question)
class Meta:
unique_together = ('ip', 'question',)
然后在count_views增加该值之前,它应该查询LastViewed表以检查上次访问时间:
question = Question.objects.get(pk=question_id)
request_ip = request.META['REMOTE_ADDR']
last = LastViewed.objects.get(ip=request_ip)
if request.is_ajax() and (last.last_view - datetime.datetime.now() < datetime.timedelta(minutes=5)):
question.views_count = question.views_count + 1
question.save()
else:
# etc
我希望这有助于您大致了解如何进行操作,我省略了实际添加/更新LastViewed表的新条目的代码。