首页 > 解决方案 > “产品”类型的对象不是 JSON 可序列化的

问题描述

我正在尝试通过 Django 从我的应用程序中提取。问题是当我通过序列化程序调用 Order Detail 时,我收到此错误:

TypeError at /api/customer/order/latest/
Object of type 'Product' is not JSON serializable
Request Method: GET
Request URL:    http://localhost:8000/api/customer/order/latest/?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Django Version: 1.10
Exception Type: TypeError
Exception Value:    
Object of type 'Product' is not JSON serializable

我正在从这个模型中提取数据:

class OrderDetail(models.Model):
    order = models.ForeignKey(Order, related_name='order_details')
    product_size = models.ForeignKey(ProductSize)
    quantity = models.IntegerField()
    sub_total = models.FloatField()

    def __str__(self):
        return str(self.id)

# references Prodcut and allows old code to work.
    @property
    def product(self):
        return self.product_size.product

这是被拉的:

'order_details': [OrderedDict([('id', 68),
                                ('product_size', 44),
                                ('quantity', 1),
                                ('sub_total', 20.0),
                                ('product', <Product: Bacon Burger - withDrink>)])],
 'status': 'Your Order Is Being Picked Right Off The Plant!',
 'total': 20.0}
request 
<WSGIRequest: GET '/api/customer/order/latest/?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX'>

序列化器:

class OrderDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderDetail
        fields = ("id", "product_size", "quantity", "sub_total", "product")


class OrderSerializer(serializers.ModelSerializer):
    customer = OrderCustomerSerializer()
    driver = OrderDriverSerializer()
    restaurant = OrderRestaurantSerializer()
    order_details = OrderDetailSerializer(many = True)
    status = serializers.ReadOnlyField(source= "get_status_display")

    class Meta:
        model = Order
        fields = ("id", "customer", "restaurant", "driver", "order_details", "total", "status", "address")

详细功能:

def customer_get_latest_order(request):
    access_token = AccessToken.objects.get(token = request.GET.get("access_token"),
    expires__gt = timezone.now())

    customer = access_token.user.customer
    order = OrderSerializer(Order.objects.filter(customer = customer).last()).data

    return JsonResponse({"order": order})

我不确定需要做什么。

标签: djangorestdjango-rest-framework

解决方案


由于模型product的属性OrderDetail返回Product对象,在响应过程中无法序列化。

要修复它,您可以返回product.id

class OrderDetail(models.Model):
    order = models.ForeignKey(Order, related_name='order_details')
    product_size = models.ForeignKey(ProductSize)
    quantity = models.IntegerField()
    sub_total = models.FloatField()

    def __str__(self):
        return str(self.id)

    @property
    def product(self):
        return self.product_size.product.id

或者,如果您需要产品的详细信息作为响应,您应该在其中添加一个嵌套序列化程序OrderDetailSerializer

class ProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = ("id", "other fields")

class OrderDetailSerializer(serializers.ModelSerializer):
    prodcut = ProductSerializer()

    class Meta:
        model = OrderDetail
        fields = ("id", "product_size", "quantity", "sub_total", "product")

推荐阅读