我嘗試通過定義過濾器類并在我的視圖中匯入來使用自定義過濾,但它不起作用。
我的代碼:
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,sonydoenst 過濾器并顯示資料庫中的所有物件時。它僅在我不這樣輸入時才有效localhost/api/products?brand___name=lg。但我需要通過多個引數進行查詢。這里有什么問題??從檔案中,它說我可以使用 __in 進行多次查詢。
uj5u.com熱心網友回復:
默認lookup_expr是exact如果你不描述一個。
您的 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']
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371712.html
標籤:姜戈 接口 Django 休息框架 抬头 django 过滤器
