首页 > 解决方案 > ProductImage 类型的对象不是 JSON 可序列化的

问题描述

我收到此错误Object of type ProductImage is not JSON serializable 我正在尝试制作模型,在该模型中我可以使用 ManytoManyFeild() 添加多个图像。然后我想对其进行序列化,以便可以将其发送到前端页面并显示。

这是我的模型

from django.db import models


class Product(models.Model):
    id = models.IntegerField(unique=True,primary_key=True)
    title = models.CharField(max_length=200)
    description = models.TextField(max_length= 100000 ,null=True, blank=True)
    price = models.FloatField()
    count = models.IntegerField(default=1)
    file_content = models.ManyToManyField("ProductImage", related_name='file_content', blank=True, null=True)

    offer= models.BooleanField(default=False)

    def __str__(self):
        return self.title

class ProductImage(models.Model):
    property_id = models.ForeignKey(Product,on_delete=models.CASCADE ,null=True, blank=True)
    media = models.FileField(upload_to='pics')
    

    def __str__(self):
        return '%s-image' % (self.property_id.title)

    

这是我的serializer.py

from rest_framework import serializers
from . models import Product, ProductImage

class ProductImageSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = ProductImage
        fields = [ 'property_id','media']
       

class ProductSerializer(serializers.ModelSerializer):
    file_content = ProductImageSerializer(many=True)

  
    class Meta:
        model = Product
        fields = ['id', 'title','description', 'price','count', 'file_content',
                    'offer']
     
    extra_kwargs = {
        "file_content": {
            "required": False,
        }
    }

这是我的Views.py

from rest_framework.serializers import Serializer
from . models import Product, ProductImage
from rest_framework.response import Response
from . serializer import ProductSerializer

from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormParser


from rest_framework.decorators import api_view, permission_classes, parser_classes
from rest_framework.permissions import IsAuthenticated


@api_view(['POST','GET'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
def ProductViews(request):
   
    if request.method == 'POST':
        files = request.FILES.getlist('file_content')
        if files:
            request.data.pop('file_content')

            serializer = ProductSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                tweet_qs = Product.objects.get(id=serializer.data['id'])
                uploaded_files = []
                for file in files:
                    content = ProductImage.objects.create(media=file)
                    uploaded_files.append(content)

                tweet_qs.file_content.add(*uploaded_files)
                context = serializer.data
                context["file_content"] = [file.id for file in uploaded_files]
                return Response(context, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            serializer = ProductSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                context = serializer.data
                return Response(context, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'GET':
        detail = [{"title": detail.title, "id": detail.id, "count": detail.count, "description": detail.description, "price": detail.price, "offer": detail.offer , "details": detail.file_content.all()}
        for detail in Product.objects.all()]
        return Response(detail)


我不知道有什么问题,所以如果可以提供帮助,我将非常感谢您。谢谢

注意:如果您知道任何其他更好的方法来制作可以包含图像列表的 Json,您也可以分享它(或其链接)。

标签: pythonjsondjangoserializationdjango-rest-framework

解决方案


这可能会帮助您:

class ProductImage(models.Model):
    property_id = models.ForeignKey(Product, on_delete=models.CASCADE ,null=True, blank=True)
    media = models.FileField(upload_to='pics')
    
    def __str__(self):
        return '%s-image' % (self.property_id.title)
   
    def media_url(self):
        return self.media.url
class ProductImageSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = ProductImage
        fields = [ 'property_id','media','media_url']

推荐阅读