anhtran
anhtran

Reputation: 2034

How to sort order in Django Related Models (Generic relations)

My models:

HitCounter:

hits  = models.PositiveIntegerField(default=0)
object_pk  = models.TextField('object ID')
content_type    = models.ForeignKey(ContentType,
                        verbose_name="content cype",
                        related_name="content_type_set_for_%(class)s",)
content_object  = generic.GenericForeignKey('content_type', 'object_pk')

Item:

title    = models.CharField(_('Title'), max_length=400)
desc     = models.TextField(_('Description'), blank=True

)

I want to sort order the items in Item by hits in HitCounter? What should I do?

Upvotes: 1

Views: 870

Answers (2)

Felix Kling
Felix Kling

Reputation: 816452

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']

Upvotes: 0

Zach
Zach

Reputation: 19082

I think this should work:

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

Doc for Django aggregation here

Upvotes: 2

Related Questions