2011-08-21 59 views
1

模型問題有一個view_counts字段來計算一個問題查看的次數。如何限制一個Django查看方法在一個時間段內工作?

和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

拿我與一粒鹽的提醒,我是相當新的Django和蟒蛇我自己,我沒有測試過這一點,但我會去實現這個像這樣:

創建新模型:

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 

我希望幫助給你h的總體思路我去掉了它,我沒有看到代碼來實際添加/更新新條目到LastViewed表。

相關問題