Home > Blockchain >  KeyError: How to exclude certain parts when a part of the serializer is empty
KeyError: How to exclude certain parts when a part of the serializer is empty

Time:11-09

I have this piece in my serializer which is using a nested serializer field. When i try to submit my form it will return a KeyError if I don't add anything inside "assigned facilities". I tried adding an else statement but that doesn't seem to be helping. The debugger is actually complaining about line two when the field is empty so how do i exclude it when there is no data submited in assigned_facilities field? I`m already using required=False, allow_null=True inside the serializer.

    def create(self, validated_data):
        assigned_facilities = validated_data.pop("assigned_facilities")
        instance = Lead.objects.create(**validated_data)

        for item in assigned_facilities:
            instance.leadfacility.create(**item)

        else:
            print("No Facilities Added!")
            
        return instance

CodePudding user response:

You can add default value in pop function, so it wont raise keyerror

    def create(self, validated_data):
        assigned_facilities = validated_data.pop("assigned_facilities", [])
        instance = Lead.objects.create(**validated_data)

        for item in assigned_facilities:
            instance.leadfacility.create(**item)

        else:
            print("No Facilities Added!")
            
        return instance
  • Related