我有一个模型想要过滤多个值。
我的模型:
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 构造为,我只能看到 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')
有一种更简单的方法可以使用django-filter package https://django-filter.readthedocs.io/en/stable/index.html。内心深处django-filter文档 https://django-filter.readthedocs.io/en/stable/ref/filterset.html#declaring-filterable-fields,它提到您可以使用“映射到查找列表的字段名称字典”。
您的代码将像这样更新:
# views.py
from django_filters.rest_framework import DjangoFilterBackend
class ProductViewSet(ModelViewSet):
queryset = models.Product.objects.all()
serializer_class = serializers.ProductSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = {
'id': ["in", "exact"], # note the 'in' field
'ean': ["exact"]
}
现在在 URL 中添加__in
在提供参数列表之前添加到过滤器,它将按您的预期工作:
www.example.com/api/Product/?id__in=1,2
The django-filter
关于可用查找过滤器的文档非常少,但是in
查找过滤器在Django 文档 https://docs.djangoproject.com/en/3.2/ref/models/querysets/#in itself.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)