views:

89

answers:

2

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?

+2  A: 

I think this should work:

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

Doc for Django aggregation here

Zach
hitcounter is not defined
Tran Tuan Anh
Tye Hitcounter.
dotty
Is your first model named 'HitCounter' and you're still getting an exception? Can you post the message?
Zach
I have took an ordered list of the id of the Item. But how to get the items from Item object with it. I have used for loop but looks not good.
Tran Tuan Anh
Sorry, I don't understand what you mean. Can you rephrase?
Zach
I have made a question in here: http://stackoverflow.com/questions/2364905/django-sort-order-the-list-in-objects. Please visit and take your points. Thanks!
Tran Tuan Anh
+1  A: 

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