Django中增加页面计数 [英] Increment Page Hit Count in Django

查看:111
本文介绍了Django中增加页面计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,一个 IntegerField hit_count ),当页面被访问时(例如,我想让数据库中的记录ID 3的 hit_count 列增加1位, http:// site / page / 3



查询应该如下所示:

 更新表set hit_count = hit_count + 1其中id = 3 

我可以用标准的Django模式约定?或者我应该手动编写查询?

解决方案

如果您使用Django 1.1+,只需使用 F表达式


 从django.db.models导入F 
...
MyModel.objects.filter(id = .. 。)。update(hit_count = F('hit_count')+ 1)

这将执行一个原子数据库查询。



如gerdemb所示,您应该考虑将其放在中间件中,使其轻松重用,这样就不会使您的所有观点混乱。 >



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 hit_count column in the database to increment by 1.

The query should be like:

update table set hit_count = hit_count + 1 where id = 3

Can I do this with the standard Django Model conventions? Or should I just write the query by hand?

解决方案

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.


这篇关于Django中增加页面计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆