Home > Mobile >  make two fields in serializer from a same model
make two fields in serializer from a same model

Time:05-12

I'm using a nested serializer in another serializer and I have two models Object and ObjectMedia see the following code:

class ObjectMediaSerializer(serializers.ModelSerializer):
    media_address = serializers.SerializerMethodField()    
    class Meta:
        model = ObjectMedia
        fields = ["media_address", "type"]

class ObjectAddEditSerializer(serializers.ModelSerializer):
   
    slug = serializers.SlugField(read_only=True)
    object_medias = ObjectMediaSerializer(many=True, required=True)

    class Meta:
        model = Program
        fields = [
            "slug",
            "object_medias",
        ]

I want to add object media in two fields(separated by their type) like below but I don't know how it is possible:

{
  "slug":"my_slug",
  "object_media_type1": [
    {
      "media_address ": "somewhere",
       "type":TYPE1
    }
  ],
"object_media_type2": [
    {
      "media_address ": "somewhere",
       "type":TYPE2
    },
      {
      "media_address ": "somewhere\else",
       "type":TYPE2
    }]
}

Thanks for reading

CodePudding user response:

You can do this using a SerializerMethodField:

class ObjectAddEditSerializer(serializers.ModelSerializer):
   
    slug = serializers.SlugField(read_only=True)
    object_media_type1 = serializers.SerializerMethodField()
    object_media_type2 = serializers.SerializerMethodField()

    def get_object_media_type1(self, instance):
        return ObjectMediaSerializer(instance.object_medias.filter(type="type1"), many=True).data

    def get_object_media_type2(self, instance):
        return ObjectMediaSerializer(instance.object_medias.filter(type="type2"), many=True).data

    class Meta:
        model = Program
        fields = [
            "slug",
            "object_media_type1",
            "object_media_type2",
        ]

Be aware that they are read-only. Official docs here.

  • Related