I am not able to use the answers here or here for my own problem. I tried to customize the DRF tutorial part 3:
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)
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",]
I expected to get a JSON like response:
{ "product_id": "213123", "price": 2.99, "product": "bacon" }
But I get the error:
Exception Type: TypeError
Exception Value: Object of type ListSerializer is not JSON serializable
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…