简体   繁体   中英

Nested Serializer in Django Rest Framework

I am trying to make a nested serializer but when I run the following code it gives me an empty list. I tried to replicate the solution of this question and my problem is exactly similar

The only difference is in that answer serializer.Serializer is used but I am using Model Serializer

class hhhSerializer(serializers.Modelserializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(read_only=True)
    class Meta:
        model = ItemBatch
        fields = ('id','name')


class dispatchhistorySerializer(serializers.ModelSerializer):

    truck_name = ReadOnlyField(source='truck_name.name')
    truck_type = ReadOnlyField(source='truck_type.name')

    items = hhhSerializer(many=True)
    class Meta:
        model = DispatchPlan
        fields = "__all__"

Output:

        "id": 35,
        "truck_name": "24 ft mxl 14 Ton",
        "truck_type": "Container",
        "items": [
            {},
            {},
            {},
            {},
            {},
            {},
            {},
            {},
            {},
            {}
        ],

You have to declare the field explicitly at DispatchHistorySerializer.Meta.fields ; now, as personal recommendation avoid always "all" in the field list

This code should work (I had renamed your classes to comform python convention)

class HhhSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(read_only=True)
    class Meta:
        model = ItemBatch
        fields = ('id','name')


class DispatchHistorySerializer(serializers.ModelSerializer):

    truck_name = ReadOnlyField(source='truck_name.name')
    truck_type = ReadOnlyField(source='truck_type.name')
    items = HhhSerializer(many=True)  # 2) here we say how to serialize 'items'

    class Meta:
        model = DispatchPlan
        fields = ('id', 'truck_name', 'truck_type', 'items',)  # 1) here we say: include 'items' please

EDIT : if using ModelSerializer , define which model in the Meta class; if it isn't a ModelSerializer, use a simple Serializer instead

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