views:

305

answers:

2

Hi. The site makes use of 2 objects - articles and blogs. Every time an article or blog is viewed, a related counter should increase by one.

The idea is to have a "top ten" application that measures the "popularity" of the articles and entries.

Because I'm using more than one object, I would like the Tracker model to use a genericForeignKey to the related objects.

#models.py
class Tracker(models.Model):
    count = models.PositiveIntegerField(default=1)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    def hit(self):
        self.count += 1

I would like to write a decorator that wraps a view function, but it might not be necessary.

Thanks

+2  A: 

If i understand you right you want to count each instantiation of every object. I would do it by using a post_init signal — if you do not mind that it is not a decorator.

Here is a code, I wrote - using post_save instead of post_init:

def thumb_init(sender, **kwargs):
    kwargs['instance'].process()
    kwargs['instance'].make_thumbnail()

post_init.connect(thumb_init, sender=Thumbnail) 
post_init.connect(thumb_init, sender=<otherModel here>)
vikingosegundo
so a post_init signal is sent whenever the db is hit with a query for an object? And by listening and responding to the signal with a counter, we can count how many times a particular "instance" has been instantiated in a view. Awesome!
Cody
This isn't the solution, but close: post_init signals are sent every time an instantiation happens in the admin too; I need to track only the user views. I'll try making a custom signal.
Cody
in your view, you could *mark* the objects as being touched by the view via monkey-patching like obj.touched = True. in a signal u would check for it (and should delete it again)
vikingosegundo
A: 

I added another answer under your original post

vikingosegundo