2016-06-15 15 views
0

我有以下型號:計數一定的選擇出現在車型數量

class Team(models.Model): 
    # stuff 
class Event(models.Model): 
    # stuff 
class Award(models.Model): 
    award_type_choices = (
     (1, "some string"), # a lot of these 
     (2, "some other str"), 
    ) 
    award_type = models.CharField(choices=award_type_choices) 
    specific_choices = (
     (1, "some string"), # etc 
     # only a few of these, but all of these can be found inside award_type_choices. 
    ) 

    event = models.ForeignKey(Event) 
    recipients = models.ManyToManyField(Team) 

我想計數/註釋的次Team數量已經贏得了specific_choices序列的下面,一個獎項。我可以過濾已通過這段代碼獲得獎項的球隊:

reversed_choices = dict((v, k) for k, v in Award.specific_choices) 
Team.objects.filter(award__award_type__in=reversed_choices.values()) 

但是,我不知道我應該怎麼計算接近這些。我之前已經使用了Count,FExpressionWrapper,但並沒有廣泛地知道如何做到這一點。

我想我可以通過拋出相同的參數filterCount對象接近它,但只要我打它,我意識到這是行不通的,即:

Team.objects.annotate(num_specifics=Count('award__award_type__in=Award.specific_choices')) 

任何幫助將不勝感激。

回答

0

我能找到一些關於Conditional Aggregation的Django文檔,幫助我解決了這個問題。

def most_specifics(): 
    reverse_specs = dict((v, k) for k, v in Award.specific_choices) 
    return Team.objects.annotate(
     c=Sum(
      Case(
       When(award__award_type__in=reverse_specs.values(), then=1), 
       default=0, 
       output_field=PositiveSmallIntegerField(), 
      ) 
     ) 
    ).order_by('-c') 
1
choices = Award.specific_choices.all() 

c = Team.objects.filter(award__award_type__in=choices).count() 
+0

對不起,我不認爲我是很清晰。我正在尋找每個團隊的「註釋」字段,這個字段的次數是他們有多少次是'specific_choices'字段的'Award'。此外,'specific_choices'只是一個在其中包含'int,str'元組的序列。無法調用'all()'。 – Justin

+0

然後它只是Team.objects.annotate(num_specifics = c),其中c是上述返回的值。 – dmitryro

+0

這不起作用; AFAIK,你不能在註釋裏面加入查詢。此外,所做的是讓許多球隊贏得這些特定獎項,而不是贏得多少獎金。我正在尋找後者。 – Justin

0

下面的代碼將找到的選項數量在一個給定的模型的某些領域:

my_field=Model._meta.get_field('field_name') 

length=len(my_field.choices._display_map)