如何在响应中添加额外字段以了解哪个项目触发了搜索结果

How can I add an extra field in the response to understand which item triggered the search result

我有两个简单的食谱和配料模型。

class Ingredient(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)

class Recipe(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)
    ingredients = models.ManyToManyField(Ingredient, related_name='recipe_ingredients')

我添加了一个用于食谱搜索的过滤器,我可以在其中添加成分 ID 作为参数。它 returns 含有这些成分的食谱。筛选如下,

class RecipeFilter(django_filters.FilterSet):
    ingredient_have = django_filters.CharFilter(method='filter_ingredient_have')

    def filter_ingredient_have(self, queryset, name, value):
        if value:
            ids = value.split(',')
            return queryset.filter(Q(ingredients__id__in=ids))
        return queryset


    class Meta:
        model = Recipe
        fields = []

url是这样的

/recipes/?ingredient_have=id1,id2

响应类似于

{
    "items": [
        {
            "id": "13261f0d-408d-4a51-9cc2-cb69ee72fe24",
            "name": "Curry",
            "ingredients": [
                {
                    "id": "08089ff8-03fb-4946-be61-659d799ca996",
                    "name": "oil"
                },
                {
                    "id": "dc9cb6f2-1810-48eb-b7a7-52a4bd9fdccb",
                    "name": "water"
                }
            ]
        }
    ]
}

目前,url 正在为我提供食谱列表,如果任何成分的 ID(任何食谱的)是 id1 或 id2。现在我想标记该特定成分 (id1/id2),以便前端了解配方在响应中的成分。我想添加一个额外的字段(在成分中),以便我可以在前端了解哪种成分触发了食谱出现在搜索结果中,例如,

{
    "id": "08089ff8-03fb-4946-be61-659d799ca996",
    "name": "oil",
    "highlight": false/true
}

“突出显示”字段在这里是虚构的,这就是我想要实现的。

希望我把问题说清楚了。可以给我一些吗suggestion/solution?

提前致谢。

您可以通过简单地修改 Ingredients() class 在您的“成分”模型中添加另一个字段。在你的情况下,你需要一个 BooleanField.

class Ingredient(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)
    highlight = models.BooleanField(default=False)

不要忘记使用迁移命令,以便将这些更改应用到数据库。

此外,添加 default=False 等字段可以防止已添加到数据库中的对象出现任何问题。您不需要手动为每个添加 ingredients 值,因为它们将被自动分配一个 False 值。

我在序列化器中解决了这个问题,

class IngredientSerializer(BaseSerializer):
    isHighlight = serializers.SerializerMethodField()
    def get_isHighlight(self, obj):
        ids = []
        if 'request' in self.context and 'ingredient_have' in self.context['request'].query_params:
            ingredient_have = self.context['request'].query_params['ingredient_have']
            if ingredient_have:
                ids.extend(ingredient_have.split(','))
        if str(obj.id) in ids:
            return True
        return False

这就是我如何获取查询参数并突出显示成分以指示此食谱出现在搜索结果中的原因。