小编Pat*_*Pel的帖子

在 Django Rest Framework 中过滤多个值

我有一个模型想要过滤多个值。

我的模型:

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)
Run Code Online (Sandbox Code Playgroud)

我要么想在“ean”字段上进行过滤,要么在主键上进行过滤,两者都可以。根据我当前的设置,我只能看到最后一个值。例如,当我将 URL 构造为www.example.com/api/Product/?id=1&id=2时,我只能看到 id 为 2 的产品,而我想查看 id 为 1 和 id 2 的产品。

我应该如何构建我的 ViewSet?目前我有:

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

filtering django-rest-framework django-rest-viewsets

5
推荐指数
1
解决办法
9698
查看次数