2012-04-09 89 views
0

如何計算對象的調用次數。例如:我有一個圖像應用程序,我想向用戶顯示圖片被調用的頻率。像YouTube上的videosviewsDjango計數對象調用

回答

2

您需要在表格中存儲計數並在每次使用圖像時增加計數。

首先,一個字段添加到您的模型,如果你沒有一個已經存儲計數:

class MyImageClass(models.Model): 
    ... 
    views = models.PositiveIntegerField(default=0) 

然後您就需要創建一個視圖,將返回圖像數據,並增加查看次數。

def my_image_view(request, id): 
    instance = get_object_or_404(MyImageClass, id=id) 

    filename, ext = os.path.splitext(instance.image_field.name) 
    ext = ext[1:].lower() # remove period and normalize to lowercase 

    instance.views += 1 
    instance.save() 

    response = HttpResponse(instance.image_field.read(), mimetype='image/%s' % ext) 
    response['Content-Disposition'] = 'inline;filename=%s.%s' % (filename, ext) 
    return response 

胡克認爲成URLPATTERN,然後在你的模板調用與圖像:

<img src="{% url my_image_view_name id=my_image.id %}"> 

你肯定會需要做一些優化了,並且有線程安全問題考慮一下,但這足以讓你的球滾動起來。

1

有沒有任何內置的方法來允許這一點。您必須將信息存儲到數據庫中