2013-10-23 31 views
0

需要對最佳情況下某些屬性值等於1,2,3和> 3的行數進行計數。 實施例:有沒有辦法在django中的一個循環中改進查詢?

for i in xrange(1,4): 
    count = some_queryset\ 
     .filter(related__value__exact=i)\ 
     .annotate(count=Count('mtopening'))\ 
     .values_list('count',flat=True) 

是否有未經raw_sql或用簡單的.extra選擇在一個面向對象的方式來提高的方法嗎?

+0

UPD。這種情況下需要3個不同的計數(1,2,3)。所以「_in」不適合。 –

回答

0

使用Django的計數方法

count = some_queryset \ 
    .filter(Q(related__value__gte=1) & Q(related__value__lt=4)).count() # This should work also without using Q() 

編輯

我不認爲這是一個直接的方式在Django做到這一點,但我認爲下面的代碼將做的工作:

sums = [] 

for i in range(1,4): 

    sums.append(
     QUERYSET.filter(related__value = i).count() 
    ) 

print sums # will show you a list of sums of the values you want     
+0

我知道它,但我需要計數值= 1的對象,計數2的值= 2並且計數值爲3,而不是一起計數。 –

+0

@ДмитрийКорнеев,請在我的答案中找到'EDIT' – securecurve

相關問題