Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

django - Serializing model data leads to TypeError "Object of type ListSerializer is not JSON serializable"

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can for this, I see you, you forget the results.data because you are using a serializer and then for the output display you have to call results.data

class ProductViewSet(viewsets.ViewSet):

    def list(self, request):
        results = ProductSerializer(Product.objects.all(), many = True)
        return Response(results.data)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...