[Answered ]-I have a field with current/permanent_address and I need to use this field with forward slash in my serializer

1👍

you can declare fields in your serializer when dealing with field names that contain forward slashes:

for example:

from rest_framework import serializers

class AddressSerializer(serializers.Serializer):
    current_permanentAddress = serializers.SerializerMethodField()
    correspondence_localAddress = serializers.SerializerMethodField()

    def get_current_permanentAddress(self, obj):
        return {
            "PERM_LINE1": obj.get("address/current/permenantAddress/PERM_LINE1", ""),
            "PERM_LINE2": obj.get("address/current/permenantAddress/PERM_LINE2", ""),
        }

    def get_correspondence_localAddress(self, obj):
        return {
            "CORRES_LINE1": obj.get("address/correspondence/localAddress/CORRES_LINE1", ""),
        }

I define two fields, current_permanentAddress and correspondence_localAddress, using SerializerMethodField. These fields call custom methods, get_current_permanentAddress, and get_correspondence_localAddress, respectively, which extract values from the nested field names with forward slashes using the obj.get() method.

Leave a comment