Nested Json is not being serialized while using Multipart Parser

南楼画角 提交于 2021-02-11 15:09:40

问题


I will try to give a small example and tell where it's not working. The models are as follows,

class Address(models.Model):
    name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)

    class Meta:
        managed = True
        db_table = 'Address'


class Product(models.Model):
    title = models.CharField(db_column='title', max_length=200, blank=False, null=False)
    imageUrl = models.ImageField(db_column='image_url', blank=True, null=True, upload_to='deals/%Y/%m/')
    addresses = models.ManyToManyField(Address, related_name='product_addresses')

    class Meta:
        managed = True
        db_table = 'Product'

The serializers

class AddressSerializer(BaseSerializer):
    id = serializers.IntegerField(required=False)
    name = serializers.CharField(required=False)

    class Meta:
        model = Address
        fields = ['id', 'name']


class ProductSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(required=False)
    addresses = AddressSerializer(many=True, required=False)

    def create(self, validated_data):
        locationData = get_popped(validated_data, 'addresses')
        instance = Product.objects.create(**validated_data)
        self.createLocation(locationData, instance)
        return instance

    def createLocation(self, locationData, instance):
        location_ids = []
        if locationData is not None:
            for item in locationData:
                if 'id' in item:
                    location_ids.append(item.get('id'))
        addresses = Address.objects.filter(id__in=location_ids)

        for loc in addresses:
            instance.addresses.add(loc)
        instance.save()

    def update(self, instance, validated_data):
            print(validated_data)
            addressData = get_popped(validated_data, 'addresses')
            if addressData is not None:
                instance.addresses.clear()
                self.createLocation(addressData, instance)

            super(self.__class__, self).update(instance, validated_data)
            return instance

    class Meta:
        model = Product
        fields = ['id', 'addresses', 'title', 'imageUrl']

My views,

class ProductViewSet(viewsets.ModelViewSet):
    pagination_class = CustomPagination
    serializer_class = ProductSerializer
    parser_classes = (MultipartJsonParser, parsers.JSONParser)
    queryset = Product.objects.all()

class AddressViewSet(viewsets.ModelViewSet):
    pagination_class = CustomPagination
    serializer_class = AddressSerializer
    queryset = Address.objects.all()

And the parser is

class MultipartJsonParser(parsers.MultiPartParser):
    def parse(self, stream, media_type=None, parser_context=None):
        result = super().parse(
            stream,
            media_type=media_type,
            parser_context=parser_context
        )
        data = {}
        # find the data field and parse it
        qdict = QueryDict('', mutable=True)
        if "product" in result.data:
            print("In Parser (result.data):")
            print(result.data)
            data = json.loads(result.data["product"])
            print("In Parser (json load):")
            print(data)
            qdict.update(data)
            print("In Parser (updated query dict):" )
            print(qdict)
        return parsers.DataAndFiles(qdict, result.files)

Now when I POST/PUT data with JSON, it works as expected. However, when I POST/PUT an image and data with address, the address does not get serialized. The request is as follows,

In the Parser class and serializer, I printed the data

Clearly, you can see that the addresses are missing in the serializer. The title is being updated. Only nested JSON is not available in the serializer. How can I get the addresses in the serializer? Thanks in advance.

来源:https://stackoverflow.com/questions/64547729/nested-json-is-not-being-serialized-while-using-multipart-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!