当我尝试访问
MultiValueDictKeyError
处的 API 时,我在 Django 项目中遇到了 http://127.0.0.1:8000/api/products/
。错误发生在这一行:category = self.request.GET['category']
。
这是我的观点:
class ProductList(generics.ListCreateAPIView):
queryset = models.Product.objects.all()
serializer_class = serializers.ProductListSerializer
def get_queryset(self):
qs = super().get_queryset()
category = self.request.GET['category']
category = models.Product.objects.get(category)
qs = qs.filter(category=category)
return qs
我的
Product
模型定义如下:
class Product(models.Model):
category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, related_name='product_in_category')
retailer = models.ForeignKey(Retailer, on_delete=models.SET_NULL, null=True)
title = models.CharField(max_length=200)
detail = models.CharField(max_length=200, null=True)
price = models.FloatField()
def __str__(self) -> str:
return self.title
这是我的序列化器:
class ProductListSerializer(serializers.ModelSerializer):
productreview = serializers.StringRelatedField(many=True, read_only=True)
class Meta:
model = models.Product
fields = ['id', 'category', 'retailer', 'title', 'detail', 'price', 'productreview']
def __init__(self, *args, **kwargs):
super(ProductListSerializer, self).__init__(*args, **kwargs)
我试图根据我的 React 前端的产品类别调用产品列表,但我不断遇到
MultiValueDictKeyError
。我尝试使用GET.get
和各种其他方法,但未能解决问题。
这是错误回溯:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/products/
Django Version: 4.2.13
Exception Type: MultiValueDictKeyError
Exception Value: 'category'
如何修复此错误并按类别正确过滤产品?
Django 在
querystring中查找
category
,但没有,所以这就是问题所在。您应该通过以下方式访问它:
http://127.0.0.1:8000/api/products/?category=14
但这仍然行不通:你应该使用类别进行过滤,所以:
class ProductList(generics.ListCreateAPIView):
queryset = models.Product.objects.all()
serializer_class = serializers.ProductListSerializer
def get_queryset(self):
category = self.request.GET['category']
return super().get_queryset().filter(category_id=category)
这将获得类别为
Product
的 pk=14
。