Herman Schaaf
Herman Schaaf

Reputation: 48445

Keeping track of how many views an object receives in Django

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.

Upvotes: 1

Views: 285

Answers (2)

Spacedman
Spacedman

Reputation: 94192

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'.

Upvotes: 1

Herman Schaaf
Herman Schaaf

Reputation: 48445

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

Upvotes: 2

Related Questions