2010-01-06 5 views
4

I했습니다있어 흐르는 두 가지 모델 : 항목 XI에 대한장고 정렬 쿼리 발생에 의해 초래

class Item(models.Model): 
    Name = models.CharField(max_length = 32) 

class Profile(models.Model): 
    user = models.ForeignKey(User, unique = True) 

    ItemList = models.ManyToManyField(Item, related_name = "user_itemlist") 

이 항목의 목록이 ITEMLIST에 X를 포함하는 모든 프로필 개체에 대한 ITEMLIST에 존재하는 개체를 얻으려면, 각 개체가 나타나는 횟수로 정렬됩니다.

Item.objects.filter(user_itemlist__in = User.objects.filter(profile__ItemList = X)) 

및 항목 Z가 10 나타납니다 개체 (10) 프로필에 대한 ITEMLIST에 존재하는 경우이 (중복와 함께, 내가 필요로하는 모든 항목 개체의 목록을 반환

지금까지 내가 할 수있는 최선이다 쿼리 결과에서 시간).

위의 쿼리 결과를 각 개체가 결과에 나타나는 횟수만큼 정렬하고 중복을 제거하려면 어떻게합니까? 거기에 "장고"방법이 있나요?

답변

7
profiles = Profile.objects.filter(profile__ItemList=X) 

Item.objects.filter(
    user_itemlist__in=profiles 
).annotate(itemcount=Count('id')).order_by('-itemcount') 
3

당신이 장고를 사용하는 경우이 작업을 수행 할 수 있습니다 1.0 이상 :

from django.db.models import Count 
# note that 'profile' is an instance of Profile, not the model itself 
sorted_items = profile.ItemList.annotate(itemcount=Count('name')) 
sorted_items = sorted_items.order_by('-itemcount') 

#number of occurences of top item 
sorted_items[0].itemcount 
+0

가 확실하지 이해,하지만 난 구문이 올바른지 생각하지 않는다 : AttributeError : 'ReverseManyRelatedObjectsDescriptor' 객체에 'annotate'속성이 없습니다. – dandu

+1

답변에 대한 영감을 얻은 것 같습니다. 아직 확실하지 않습니다. 'id')).) order_by ('- itemcount') – dandu

+0

그 오류는 귀하가 미국인임을 의미합니다. ng Profile (그리고 인시던트가있는 클래스) – Jiaaro