Increment Page Hit Count in Django

前端 未结 4 948
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 08:46

I have a table with an IntegerField (hit_count), and when a page is visited (for example, http://site/page/3) I want record ID 3\'s

4条回答
  •  醉酒成梦
    2020-12-29 09:18

    If you use Django 1.1+, just use F expressions:

    from django.db.models import F
    ...
    MyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1)
    

    This will perform a single atomic database query.

    As gerdemb says, you should consider putting this in a middleware to make it easily reusable so it doesn't clutter up all your views.


提交回复
热议问题