且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django:如何计算观看的人数

更新时间:2023-12-02 18:16:40

我想你可以通过cookie做这两件事。例如,当用户访问某个网页时,您可以

I think you can do both things via cookies. For example, when user visits a page, you can


  1. 检查他们是否有seen_post_%s

  1. Check if they have "viewed_post_%s" (where %s is post ID) key set in their session.

如果有,则不执行任何操作。如果没有,请将对应的 Post 对象的 view_count 数字字段增加一,并设置键)

If they have, do nothing. If they don't, increase view_count numeric field of your corresponding Post object by one, and set the key (cookie) "viewed_post_%s" in their session (so that it won't count in future).

现在使用Django使用Cookie(工作阶段)时,很容易:为当前用户设置一个值,只需调用

Now using cookies (sessions) with Django is quite easy: to set a value for current user, you just invoke something like

request.session['viewed_post_%s' % post.id] = True

(请检查文档,特别是示例。)

in your view, and done. (Check the docs, and especially examples.)

免责声明:这是我的头,我没有做这个个人,通常当有需要做一些页面查看/活动跟踪(以便你看到什么驱动更多的流量到您的网站,当用户更活跃等),那么在使用一个专门的系统(例如,Google Analytics,StatsD)有一点。但对于一些特定的用例,或作为一个练习,这应该工作。

Disclaimer: this is off the top of my head, I haven't done this personally, usually when there's a need to do some page view / activity tracking (so that you see what drives more traffic to your website, when users are more active, etc.) then there's a point in using a specialized system (e.g., Google Analytics, StatsD). But for some specific use case, or as an exercise, this should work.