两个型号的一个过滤器

时间:2015-07-09 17:10:41

标签: python django python-2.7 django-rest-framework

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

我有两个模型

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

有一个问题:我可以通过类别(食谱模型)进行食谱查询过滤,例如成分' id (RecipeIngredients模型),那么这将是一个查询?

例如:

  

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

主要问题是类别字段在Recipe模型中,但成分' id 在RecipeIngredients模型中,但每种成分都是指食谱ID。

1 个答案:

答案 0 :(得分:0)

您可以在视图中覆盖get_queryset()方法。我们首先将具有recipe_ids值的ingredient_id列表作为从查询参数接收的ingredient_id值之一。然后,我们将recipe_id值中的所有食谱作为recipe_idscategory中的值过滤为查询参数中收到的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)