2012-10-15 2 views
0

컨텐츠의 진부화를 소개하면서 아이템 쿼리 세트를 정렬해야합니다. (내용은 Items 클래스와 관련된 ManytoMany입니다.) 주석 내에서 pub_date로 내용을 필터링 할 수 있습니까?Django : 특정 필터링 된 필드를 사용하여 쿼리 세트 주문

내 코드는 모든 콘텐츠 게시일에 사용됩니다. "pub_date> '2012-10-10'"(예를 들어) 작업하려면 주석 함수가 필요합니다.

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

답변

0

그냥 필터링 후 주석 수 :

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

나는 작동하지 않는 여분의() 함수로 필터링했습니다.
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로 콘텐츠를 필터링 한 다음 content__count로 항목을 정렬하고 싶습니다. – guillaumekal

+0

죄송하지만 무슨 뜻인지 모르겠군요. 내 코드를 pub_date로 필터링 한 다음 content__count로 정렬하십시오. 내가 놓친 게 있니? – esauro

+0

콘텐츠 및 항목은 ManytoMany 관계가있는 두 개의 다른 클래스입니다. 그래서 그들은 같은 방식으로 필터링하지 않습니다. – guillaumekal

관련 문제