两种型号的一种过滤器

One Filter for Two models

我是 Django REST Framework 的新手,所以我有一个问题。

我有两个型号:

class Recipe(models.Model):
    recipe_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    category = models.ForeignKey(FoodCategory)
    .....

class RecipeIngredients(models.Model):
    ri_id = models.AutoField(primary_key=True)
    recipe_id = models.ForeignKey(Recipe)
    ri_number = models.IntegerField()
    ingredient_id = models.ForeignKey(Ingredient)
    .....

Serializer.py:

class RecipeSerializer(serializers. ModelSerializer):
    class Meta:
        model = Recipe
        fields = ('recipe_id', 'title', 'category',....)

class RecipeIngredientSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecipeIngredients
        fields = ('ri_id', 'recipe_id', 'ri_number', 'ingredient_id', ...)

每个的输出:

{"recipe_id":1,"title":"Recipe1","category":1, ....} # Recipe

[{"ri_id":15,"recipe_id":1,"ri_number":1,"ingredient_id":6,},
{"ri_id":16,"recipe_id":1,"ri_number":2,"ingredient_id":7,....}] # RecipeIngredients

有一个问题:我可以通过 类别(配方模型)进行 配方 查询过滤,例如 Ingredients' id(RecipeIngredients 模型),所以这将是一个查询?

例如:

http://127.0.0.1/api/recipes?category=category_name&ingredients=[ingred_list]

主要问题,category 字段在 Recipe 模型中,但 ingredients' id 在 RecipeIngredients 模型中,但每个成分都引用到食谱 ID。

您可以在您的视图中覆盖 get_queryset() 方法。我们首先获得 recipe_ids 的列表,其中 ingredient_id 值作为从查询参数接收到的 ingredient_id 值之一。然后我们过滤所有具有 recipe_id 值的食谱作为 recipe_ids 中的值和 category 作为查询参数中收到的 category 的值。

def get_queryset(self):
    category = self.request.query_params['category']
    ingredient_ids = self.request.query_params['ingredients[]'] # [] because getting multiple values for a same key
    recipe_ids = RecipeIngredients.objects.filter(ingredient_id__in=ingredient_ids).values_list('recipe_id', flat=True)
    return Recipe.objects.filter(recipe_id__in=recipe_ids, category=category)