2013-10-05 74 views
0

我想訂購entry_count,但它似乎(從Django錯誤)我只能按名稱和狀態排序。在這個例子中,我如何訂購entry_count?由於Django從一個方法的queryset命令

Category.objects.filter(status='Published').order_by('-entry_count') 

Model.py

class Category(models.Model): 
    """ 
    Entry Categories. 
    """ 
    name = models.CharField(max_length=60, help_text="Title of Category") 
    status = models.CharField(max_length=16, choices=STATUS_CHOICES, 
           default="Draft",) 
    @property 
    def entry_count(self): 
     return Entry.objects.filter(category=self.id).count() 

回答

1

您可以通過使用aggregation做到這一點:

from django.db.models import Count 
Category.objects.annotate(
    entry_count=Count('entry_set') 
).order_by('-entry_count') 

這樣,你會得到一個查詢中所有的計數和所有類別對象將有entry_count,因此您可以從模型中刪除@property