[Answered ]-How to sort order in Django Related Models (Generic relations)

2👍

I think this should work:

items = Item.objects.annotate(hits=Sum('hitcounter__hits')).order_by('-hits')

Doc for Django aggregation here

👤Zach

0👍

Maybe the meta options order_with_respect_to and ordering help, if you want to have this ordering by default.

Your model would look like this then:

class HitCounter:
    # properties here

    class Meta:
        order_with_respect_to: 'content_object'  # not sure if this really works
        ordering: ['-hits']

Leave a comment