2012-10-15 106 views
0

我需要对项目queryset进行排序,引入内容过时。 (内容与ManytoMany与Item类相关)。 是否可以在注释中通过pub_date过滤内容?Django:使用特定的过滤字段对Queryset进行排序

我的代码适用于每个内容发布日期。我需要注释函数来为“pub_date>'2012-10-10'”(例如)工作。

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

我试着用额外的()函数,它不起作用过滤:

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

回答

0

你可以只过滤,然后注释。

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

比方说,你的模型看起来像这样

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 

在我的测试,我加3页的内容,和两个项目。具有ID 1的项目通过内容多对多与具有ID 1的内容有关系。 id为2的项目通过内容多对多与id 2和3的内容有关系。

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

正如所料。

+0

好的,但我的问题有点不同。我想通过pub_date过滤内容,然后按内容对项目进行排序.__count – guillaumekal

+0

对不起,但我看不出您的意思。通过我的代码,您可以通过pub_date进行过滤,然后通过content__count进行排序。我错过了什么吗? – esauro

+0

内容和项目是具有ManytoMany关系的2个不同类。所以他们不会以相同的方式过滤。 – guillaumekal

相关问题