论“过滤”在姜戈框架中的多重价值 [英] Filter on multiple values in Django Rest Framework

查看:32
本文介绍了论“过滤”在姜戈框架中的多重价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要对多个值进行过滤操作的模型。

我的型号:

class Product(models.Model):
    ean = models.CharField(max_length=13, unique=True)
    product_id = models.CharField(max_length=20, null=True, blank=True)
    product_image = models.URLField(max_length=300, null=True, blank=True)
    product_title = models.CharField(max_length=300, null=True, blank=True)

我想在‘ean’字段上或在主键上使用过滤,两者都可以。使用我当前的设置,我只看到最后一个值。例如,当我将URL构造为www.example.com/api/Product/?id=1&id=2时,我只能看到id为2的产品,而我希望看到id为1和id为2的产品。

我应该如何构造我的视图集? 当前我有:

class ProductViewSet(ModelViewSet):
    queryset = models.Product.objects.all()
    serializer_class = serializers.ProductSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields  = ('id','ean')

推荐答案

使用django-filter package可以更简单地实现这一点。在django-filter documentation中,它提到您可以使用";一个映射到查找列表的字段名称字典。

您的代码将按如下方式更新:

# views.py

from django_filters.rest_framework import DjangoFilterBackend

class ProductViewSet(ModelViewSet):
    queryset = models.Product.objects.all()
    serializer_class = serializers.ProductSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = {
        'id': ["in", "exact"], # note the 'in' field
        'ean': ["exact"]
    }

现在在url中,您可以在提供参数列表之前将__in添加到过滤,它将按照您的预期工作:

www.example.com/api/Product/?id__in=1,2

有关可用的查找筛选器的django-filter文档相当差,但是in查找过滤在Django documentation本身中有提及。

这篇关于论“过滤”在姜戈框架中的多重价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆