我已阅读this和this,但它们不能解决我的问题,因为它们会将最终“计数”与数字进行比较硬编码。我想比较一个数字,它是配方本身所有成分的总和。Django filter queryset __in for * every * item in list(2.0)
让我们想象一下,我的冰箱里有一些配料,有他们的id(= id的数组)。我想看看我能做什么。我有我的模式是这样的:
class Ingredient(models.Model):
label = models.CharField(max_length=200, null=True, blank=True,
default=None)
description = models.TextField(null=True, blank=True, default=None)
class Unit(models.Model):
label = models.CharField(max_length=200, null=True, blank=True,
default=None)
abbr = models.CharField(max_length=20, null=True, blank=True,
default=None)
class IngredientUnit(models.Model):
ingredient = models.ForeignKey(Ingredient, null=False, blank=True)
unit = models.ForeignKey(Unit, null=False, blank=True)
measurable = models.BooleanField(default=True, null=False, blank=True)
is_int = models.BooleanField(default=True, null=False, blank=True)
value = models.FloatField(null=True, blank=True, default=0.0)
class Recipe(models.Model):
label = models.CharField(max_length=200, null=True, blank=True,
default=None)
description = models.TextField(null=True, blank=True, default=None)
ingredients = models.ManyToManyField(IngredientUnit)
我想做到这一点:“选择具有所有所有配方”的成分的PK阵列的成分。例如:“经典香草蛋糕”有以下成分:鸡蛋,通用面粉,发酵粉,小苏打,黄油,糖,香草,酪乳。如果有人失踪,“经典香草蛋糕”不应出现在查询结果中。相反,如果有更多的成分比那些要求,“经典香草蛋糕”应始终在最终的查询。
到目前为止,我已经完成了这项工作,但它不工作。
ingredient_ids = self.request.POST.getlist('ingredient[]', [])
if len(ingredient_ids):
recipes = Recipe.objects\
.filter(ingredients__in=ingredient_ids)\
.annotate(nb_ingredients=Count('ingredients'))\
.filter(nb_ingredients=len(ingredient_ids))
print([a for a in recipes])
的问题是,nb_ingredients=len(ingredient_ids)
应该nb_ingredients=the number of the ingredients of the current recipe
我怎样才能做到这一点?
问题还没有扣我呢。你想得到一个配方r与所有成分(例如ingredient_ids)? – Sagar
我想你只是想在过滤器之前加上注释,以便每个食谱都注明它包含的成分数量。 – Brobin
@Sagar我更新了我的问题:我的冰箱里有一些食材,里面有他们的id(= id的数组)。我想看看我能做什么。我想比较一个数字,它是配方本身所有成分的总和。 –