Keeping track of how many views an object receives in Django

倖福魔咒の 提交于 2020-01-14 03:06:34

问题


For statistical purposes, I need to keep a log of each time a certain instance of a Model is viewed in Django. I started off by creating a separate model, Stats, that contains a ManyToMany field to another Model that stores the date and time of the access. Every time the object is accessed in a view, I update the associated Stats object.

There are 2 problems with this approach (if not more):

  1. It violates the principle of not writing any data on a GET request.
  2. More importantly, it's really slow, especially because several objects can be viewed at once. This results in a visible delay when the page is loaded.

So my question is, is there a better way of doing this? If not, what techniques are available to speed things up, such as delayed writes to the DB? I've never worked with that kind of thing in Django, so any advice would be appreciated.


回答1:


Right, well, it seems Celery looks like a good option.




回答2:


Don't worry about (1). Wikipedia says:

Safe methods Some methods (for example, HEAD, GET, OPTIONS and TRACE) are defined as safe, which means they are intended only for information retrieval and should not change the state of the server. In other words, they should not have side effects, beyond relatively harmless effects such as logging, caching, the serving of banner advertisements or incrementing a web counter. Making arbitrary GET requests without regard to the context of the application's state should therefore be considered safe.

I would say keeping a count of views counts as 'mostly harmless'.



来源:https://stackoverflow.com/questions/4773694/keeping-track-of-how-many-views-an-object-receives-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!