Django 序列化模型数据会导致TypeError“;ListSerializer类型的对象不可JSON序列化;
我无法使用答案或解决我自己的问题。我尝试自定义: models.py:Django 序列化模型数据会导致TypeError“;ListSerializer类型的对象不可JSON序列化;,django,django-rest-framework,Django,Django Rest Framework,我无法使用答案或解决我自己的问题。我尝试自定义: models.py: class ProductData(models.Model): product_id = models.CharField('device_id', max_length = 20) price = models.DecimalField('price') product = models.ForeignKey(Product, on_delete = models.CASCADE) v
class ProductData(models.Model):
product_id = models.CharField('device_id', max_length = 20)
price = models.DecimalField('price')
product = models.ForeignKey(Product, on_delete = models.CASCADE)
views.py:
class ProductViewSet(viewsets.ViewSet):
def list(self, request):
data = [{"products": Product.objects.all(),}]
results = ProductSerializer(data = data, many = True)
if results.is_valid():
return Response(results)
serializers.py:
class ProductSerializer(serializers.ModelSerializer):
product_id = serializers.CharField(max_length = 20)
price = serializers.DecimalField(max_digits = 10)
product = serializers.RelatedField(many=True)
class Meta:
model = ProductData
fields = ["product_id", "price", "product",]
我希望得到类似JSON的响应:
{ "product_id": "213123", "price": 2.99, "product": "bacon" }
但我得到了一个错误:
Exception Type: TypeError
Exception Value: Object of type ListSerializer is not JSON serializable
我明白了,您可以为此忘记results.data,因为您使用的是序列化程序,然后对于输出显示,您必须调用results.data
class ProductViewSet(viewsets.ViewSet):
def list(self, request):
results = ProductSerializer(Product.objects.all(), many = True)
return Response(results.data)
我明白了,您可以为此忘记results.data,因为您使用的是序列化程序,然后对于输出显示,您必须调用results.data
class ProductViewSet(viewsets.ViewSet):
def list(self, request):
results = ProductSerializer(Product.objects.all(), many = True)
return Response(results.data)
这仅在调用
结果时有效。是否有效()
对吗?您可以在需要创建新数据时调用是否有效,因为获取不需要的数据是有效的这仅在调用结果时有效。是否有效()
对吗?您可以在需要创建新数据时调用是否有效,因为获取不需要的数据是有效的