自定义过滤在 Django 休息框架中不起作用

custom filtering not working in django rest framework

我尝试通过定义过滤器 class 并在我的视图中导入来使用自定义过滤,但它不起作用。

我的代码:

class ProductAPIView(ListAPIView):
    permission_classes = [AllowAny]
    serializer_class = ProductSerializer
    queryset = Product.objects.all()
    filter_backends = [DjangoFilterBackend]  
    filterset_class = ProductFilter
    pagination_class = CustomPagination

我的过滤器:

class ProductFilter(filters.FilterSet):
   variants__price = filters.RangeFilter()

   class Meta:
      model = Product
      fields = ['brand__name','variants__price','availability','slug','category__name',
                       'services','featured','best_seller','top_rated']

我的模特:

class Brand(models.Model):    
    name = models.CharField(max_length=100, unique=True)
    featured = models.BooleanField(default=False)


class Product(models.Model):
    
    merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
    category = models.ManyToManyField(Category, blank=False)
    sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
    mini_category = models.ForeignKey(Minicategory, on_delete=models.SET_NULL, blank=True, null=True)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
    featured = models.BooleanField(default=False)  # is product featured?
   

现在,当我调用 localhost/api/products?brand___name__in=lg,sony 时,它会过滤并显示数据库中的所有对象。它仅在我不这样输入时才有效 localhost/api/products?brand___name=lg 。但是我需要通过多个参数进行查询。这里有什么问题??从文档中,它说我可以使用 __in.

进行多重查询

默认 lookup_exprexact 如果你不描述的话。

您的 FilterSet 应如下所示:

class ProductFilter(filters.FilterSet):
   variants__price = filters.RangeFilter()

   class Meta:
      model = Product
      fields = {
        'brand__name': ['exact', 'in'],
        'variants__price': ['exact'],
        'availability': ['exact'],
        'slug': ['exact'],
        'category__name': ['exact'],
        'services': ['exact'],
        'featured': ['exact'],
        'best_seller': ['exact'],
        'top_rated': ['exact']
      }