我有一个
models.py
看起来像这样
class Product(models.Model):
name = models.CharField(max_length = 255, unique = True, null = False, blank = False)
brand = models.ForeignKey(Brand, on_delete = models.SET_NULL, null = True, blank = True, related_name = 'products')
class Brand(models.Model):
name = models.CharField(max_length = 255, unique = True, null = False, blank = False)
我想根据
name
模型的Brand
字段过滤Products的数据。我的views.py
长这样
class ProductAPIView(generics.GenericAPIView):
serializer_class = ProductSerializer
queryset = Product.objects.all()
filter_backends = (DjangoFilterBackend,)
filterset_class = ProductFilter
def get(self, request):
products = self.filter_queryset(self.get_queryset())
serializer = self.serializer_class(products, many = True)
return Response(serializer.data)
我的
filters.py
看起来像这样
class ProductFilter(FilterSet):
class Meta:
model = Product
fields = {
'brand__name' : ['iexact', ]
}
无论我为
brand
发送什么查询参数,它都会产生整个列表而不是过滤所需的列表。
我在这里遗漏了什么吗?提前致谢
你应该过滤:
?brand__name__iexact=mybrand
然而,做一个专门的领域可能更好,比如:
from django_filters import CharFilter
class ProductFilter(FilterSet):
brand = CharFilter(field_name='brand__name', lookup_expr='iexact')
class Meta:
model = Product
fields = {}
然后你过滤:
?brand=mybrand