如何使用ManyToManyField中的常见ID数注释查询集

问题描述

我有以下型号:

class Ingredient(models.Model):
    id = models.CharField(primary_key=True,max_length=24)
    name = models.CharField(max_length=100)

class Recipe(models.Model):
    id = models.CharField(primary_key=True,max_length=24)
    name = models.CharField(max_length=100)
    ingredients = models.ManyToManyField(to=Ingredient)

以及具有有效成分ID的列表,例如:

ing_id_list = ['5d481cf3abe2d800150de7b6','5c8c05bee3f3391eda4320b2',...]

我被困在带有带注释字段的查询集的构建中,该字段用常见的相关成分ID和列表中的ID丰富了食谱:

annotated_recipe_queryset = Recipe.objects.annotate(no_of_common_ings=Count(##PLEASE HELP##))

有人可以帮忙吗?

解决方法

如果使用的是Django> = 1.8,则可以使用条件聚合。对于您的示例,查询可能是:

from django.db.models import Count,Case,When,IntegerField
annotated_recipe_queryset = Recipe.objects.annotate(
        no_of_common_ings=Count(Case(When(
            ingredients__id__in=ing_id_list,then=1),output_field=IntegerField(),)))