【问题标题】:Serializing model data leads to TypeError "Object of type ListSerializer is not JSON serializable"序列化模型数据导致 TypeError “ListSerializer 类型的对象不是 JSON 可序列化的”
【发布时间】:2021-01-12 22:46:25
【问题描述】:

我无法将答案 herehere 用于我自己的问题。我尝试自定义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",]   

我希望得到类似 JSON 的响应:

{ "product_id": "213123", "price": 2.99, "product":  "bacon" }

但我得到了错误:

Exception Type:     TypeError
Exception Value:    Object of type ListSerializer is not JSON serializable

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    你可以为此,我看到你了,你忘记了 results.data,因为你使用的是序列化程序,然后为了输出显示你必须调用 results.data

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

    【讨论】:

    • 这仅在调用results.is_valid() 时有效,对吧?
    • 创建新数据时可以调用is_valid,获取数据不需要is_valid
    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2019-11-21
    • 2021-11-13
    相关资源
    最近更新 更多