简体   繁体   中英

Django REST Framework: nested serializers and deserializing

I'm again stuck with Django REST Framework and its serializers.

Basically, what I want to be able to do is stick the following incoming data into a serializers.Serializer instance:

data = {
    "thing_id": 715,
    "sub_things": [
        {
            "id": 1,
            "name": "bob"
        },

        {
             "id": 2,
             "name": "mike"
        }
    ]
}

sub_things are handled by a serializers.ModelSerializer called SubThingSerializer. This is how it looks like.

class SubThingSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubThing
        fields = ('id', 'name')
        read_only_fields = ('id', 'name')

Serialization of Thing is handled by a ThingSerializer, which I've for now handled as below:

class ThingSerializer(serializers.Serializer):
    thing_id = serializers.IntegerField()
    sub_things= SubThingSerializer(many=True)

Now, when I do

serializer = ThingSerializer(data=data)

I get empty OrderedDicts like:

{'sub_things': [OrderedDict(), OrderedDict()], 'thing_id': 715}

I guess it's wise to say that ThingSerializer will not need to get stored into a database, but it does use sub_things from database. These will not be written into db either. This is just to keep track of what sub_things the thing contains, pass this data back and forth between a browser client and a Python object for some calcualtions. And maybe store it in the session.

edit 1:

Most likely there's something I need to add to the create method of my ThingSerializer. So, I guess the ultimate question is: what's the correct syntax to pass sub_thing data to SubThingSerializers?

edit 2:

I dug a bit more. Seems that empty OrderedDicts get passed in validated_data to ThingSerializer.create() for some reason. Serializer validates alright with serializer.is_valid(). I could access the necessary data from initial_data, but that doesn't seem very solid.

edit 3:

Also tested around with serializers.ListField() for sub_things. Still seeing empty OrderedDicts in validated_data inside the create method.

Finally figured this out. read_only_fields on my SubThingSerializer prevented the data from getting through the validation resulting in empty dicts being created. I used read_only_fiels to prevent non-existent sub_thing data from being passed to my code, but I guess I'll need to find another way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM