计算模型中某些选择的出现次数

时间:2016-06-15 00:21:22

标签: python django python-3.x django-queryset

我有以下型号:

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())

但是,我不确定如何计算这些。我以前稍微使用过CountFExpressionWrapper,但并没有广泛地知道如何立即执行此操作。

我想我可以通过将filter相同的参数放到Count对象中来接近它,但是一旦我输入它,我就意识到它不会起作用,即:

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

对此有任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

choices = Award.specific_choices.all()

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

答案 1 :(得分: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')

答案 2 :(得分:0)

以下代码将在给定模型的某个字段中找到多个选项:

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

length=len(my_field.choices._display_map)