views:

16

answers:

1

Related models:

models.py

class Entry(models.Model):
    ...

class EntryView(models.Model):
    entry = models.ForeignKey(Entry)
    dt_clicked = models.DateTimeField(auto_now_add=True)
    ip = models.CharField(max_length=15, db_index=True, blank=True)
    host = models.CharField(max_length=64, db_index=True, blank=True)
    referer = models.CharField(max_length=64, db_index=True, blank=True)

    def __unicode__(self):
        return "%s -> %s" % (self.ip, self.entry.headline)

I guess I could do something like this:

views.py

...
popular = Entry.articles.values('ip').annotate(Count("entry_views__id")).order_by()
...

But I can't see how this would work since there is no field for EntryView in Entry.

+1  A: 

You can do the following:

popular = Entry.objects.annotate(count = 
     Count("entryview__ip")).order_by('-count')

I tested this using the two models you gave above. This will return a list of Entry instances annotated with the EntryView.ip count for each instance, ordered in the descending order of count (most popular first).

Manoj Govindan
Thanks, it works :)
Arnar Yngvason
uhm, nope, this does not group by ip.
Arnar Yngvason
popular = Entry.objects.annotate(count=Count("entryview__ip", distinct=True)).order_by('-count')
Arnar Yngvason