我已经安装了DjangoFilterBackend
,希望可以在category
字段上进行过滤以返回该类别的产品列表。
但是,每当我在邮递员中发送查询时。我收到错误Select a valid choice. That choice is not one of the available choices.
。
我已经尝试过滤product
模型中的另一个字段(例如name
),并且效果很好。因此,我不确定是否缺少category
可用的功能。
Product/View.py
:
class ProductView(ListAPIView):
serializer_class = ProductSerializer
queryset = Product.objects.all()
filter_backends = [DjangoFilterBackend]
filterset_fields = ('category', 'name')
Products/Models.py
:
class Product(models.Model):
name = models.CharField(max_length=250, unique=True, blank=False)
photo = models.ImageField(upload_to=product_photo_path)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
quantity = models.IntegerField()
description = models.TextField(blank=False)
price = models.DecimalField(max_digits=6, decimal_places=2)
in_stock = models.BooleanField(default=False)
trending = models.BooleanField(default=False)
def __str__(self):
return self.name
Products/serializers.py
class ProductSerializer(serializers.ModelSerializer):
category = serializers.CharField(source='category.name', read_only=True)
class Meta:
model = Product
fields = ('category', 'name', 'photo', 'quantity', 'description', 'price', 'in_stock', 'trending')
我正在使用的查询是对GET请求:
http://127.0.0.1:8000/api/products?category=xxxx - I am sending no payload. The response I am receiving is a `400 Bad Request` and the exact error is:
{
"category": [
"Select a valid choice. That choice is not one of the available choices."
]
}
我有两个模型(产品和类别),每个产品都有一个链接的类别。我已经安装了DjangoFilterBackend,希望对类别字段进行过滤以返回...
category_id
进行过滤,该字段是为FK字段自动创建的