[Django]-Django querying top weekly hits in a Database

4👍

Never used this package, but after checking the models definition, they use GFK to store hitcounts for any or your models, so in order to filter/annotate on their models you can define your own reverse relation

from django.contrib.contenttypes.fields import GenericRelation

class MyModel(models.Model):
    # ..

    hitcounts = GenericRelation(
        HitCount,
        content_type_field='content_type',
        object_id_field='object_pk',
    )

Now having this try to get your most visited models for some period using this queryset:

period = timezone.now() - timedelta(days=7)
top_models = MyModel.objects.filter(
        hitcounts__hit__created__gte=period
    ).annotate(
        counts=models.Count('hitcounts__hit')
    ).order_by('-counts')
👤Todor

Leave a comment