方法对象不是 JSON 可序列化的

method object is not JSON serializable

我正在使用 ajax 在购物车商品被移除时刷新购物车商品。它运行良好,如果我不使用图像响应对象,否则我会收到错误 method object is not JSON serializable。如果我对图像部分使用 model_to_dict,我会得到一个错误 'function' object has no attribute '_meta'

这是代码

def cart_detail_api_view(request):
    cart_obj, new_obj = Cart.objects.new_or_get(request)
    products = [{
            "id": x.id,
            "url": x.get_absolute_url(),
            "name": x.name,
            "price": x.price,
            "image": x.first_image
            }
            for x in cart_obj.furnitures.all()]
    cart_data  = {"products": products, "subtotal": cart_obj.sub_total, "total": cart_obj.total}
    return JsonResponse(cart_data)

class Furniture(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    manufacturer = models.ForeignKey(Manufacturer, blank=True, null=True)
    slug = models.SlugField(max_length=200, unique=True)

    def __str__(self):
        return self.name

    def first_image(self):
        """
        Return first image of the furniture otherwise default image
        """
        if self.furniture_pics:
            return self.furniture_pics.first()
        return '/static/img/4niture.jpg'

class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    furnitures = models.ManyToManyField(Furniture, blank=True)

我在将 x.first_image 包装到 model_to_dict

时遇到 'function' object has no attribute '_meta' 错误

我该如何解决此类问题?

已更新

class FurniturePic(models.Model):
    """
    Represents furniture picture
    """
    furniture = models.ForeignKey(Furniture, related_name='furniture_pics')
    url = models.ImageField(upload_to=upload_image_path)

如您所知,问题出在:

"image": x.first_image

first_image是函数,不能转成JSON。您要做的是序列化由 first_image 编辑的值 return。因此,为此,您需要调用这个函数:

"image": x.first_image() # note the brackets

此外,我还注意到另一个问题,地址:

return self.furniture_pics.first() # will return the image object; will cause error

因此,您必须将其更改为:

return self.furniture_pics.first().url # will return the url of the image

更新:

self.furniture_pics.first().url 将 return FurniturePic.url 这是一个 ImageField。您需要该图片的 url 进行连载。你必须这样做:

return self.furniture_pics.first().url.url # call url of `url`

如您所见,这变得令人困惑。我建议将 FurniturePic.url 字段的名称更改为 FurniturePic.image。但是,请随意忽略它。