Skip to content

Creating multiple objects with drf-writable-nested WritableNestedModelSerializer not creating the nested relation objects #166

@akhilmathew001

Description

@akhilmathew001
class AlarmListSerializer(serializers.ListSerializer):

    @classmethod
    def many_init(cls, *args, **kwargs):
        # Instantiate the child serializer.
        kwargs['child'] = cls()
        # Instantiate the parent list serializer.
        return AlarmListSerializer(*args, **kwargs)

    def create(self, validated_data):
        ret = []
        for item in validated_data:
            alarm_obj = self.child.create(item)
            ret.append(alarm_obj)
        return ret

class AlarmSerializer(WritableNestedModelSerializer):

    trigger = AlarmTriggerTimeSerializer(many=True, required=True)
    notification = AlarmNotificationUsersSerializer(many=True, required=True)
   
    class Meta:
        model = Alarm
        list_serializer_class = AlarmListSerializer
        fields = ['process',  'above_limit',
                  'below_limit', 'is_expired',
                  'is_active', 'trigger', 'notification']

    def create(self, validated_data):
        ['.. Some code ...']
        ret = super().create(validated_data)
        return ret

    def update(self, instance, validated_data):
        ['.. Some code ...']
        ret = super().update(instance, validated_data)
        return ret

I have a serializer like this. I used to pass multiple objects with nested relations to this serializer with many=True enabled from the view.
Sample JSON is as follows;

[{
        ----- Some fields ----
		"process": 32,
		"above_limit": 21,
		----- Some fields ----
		"trigger": [{
			"name": "test",
			"threshold": 4
		}],
		"notification": [{
			"email": "test@email.com"
		}]
	},
	{
	  	----- Some fields ----
		"process": 38,
		"above_limit": 22,
		----- Some fields ----
		"trigger": [{
			"name": "test",
			"threshold": 8
		}],

		"notification": [{
			"email": "test@email.com"
		}]
	}
]

Here Alarm object is getting created, but its nested relations are not created. What can be wrong here

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions