0

I need to sort the items queryset, introducing the obsolescence of content. (Content is ManytoMany related with Item class). Is it possible to filter the contents by pub_date within an annotation?

My code works here for every content publication date. I need the annotate function to work for "pub_date > '2012-10-10'" (for example).

self.queryset = Item.objects.all()    
self.queryset = self.queryset.annotate(
                Count("content")).order_by("-content__count")

I tried to filter with the extra() function, which doesn't work:

self.queryset = self.queryset.extra(select={
'content': "pub_date > '2012-10-10'"}).annotate(
Count("content")).order_by("-content__count")

1 Answers1

0

You could just filter and then annotate.

self.queryset = Items.objetct.filter(content__pub_date__gt = '2012-10-10')
self.queryset = self.queryset.annotate(
    Count("content")).order_by("-content__count")

Let's say your models looks like this

class Content(models.Model):
    pub_date = models.DateTimeField()

    def __unicode__(self):
        return "%s" % self.id

class Item(models.Model):
    content = models.ManyToManyField(Content)

    def __unicode__(self):
        return "%s" % self.id

In my test, I added 3 contents, and two items. The item with id 1 has a relation with content with id 1 via content many to many. The item with id 2 has a relation with contents with id 2 and 3 via content many to many.

>>> Item.objects.filter(
        content__pub_date__gt ='2012-10-10').annotate(
        Count("content")).order_by("-content__count")
>>> [<Item: 2>, <Item: 1>]

As expected.

esauro
  • 1,276
  • 10
  • 17
  • Ok but my problem is a bit different. I would like to filter the content by pub_date, and then sorting the items by content__count – guillaumekal Oct 15 '12 at 15:11
  • I'm sorry but I don't see what you mean. With my code you filter by pub_date, and then order by content__count. Am I missing something? – esauro Oct 15 '12 at 15:14
  • Content and Item are 2 different classes with a ManytoMany relationship. So they're not filtering the same way. – guillaumekal Oct 15 '12 at 15:20
  • @guillaumekal I edit original answer to show you how it works. I think it is correct. – esauro Oct 15 '12 at 16:05