开发者

order objects by most unique views (stored in another table with ip) in django

开发者 https://www.devze.com 2023-01-18 10:49 出处:网络
Related models: models.py class Entry(models.Model): ... class EntryView(models.Model): entry = models.ForeignKey(Entry)

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

开发者_Go百科
...
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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消