django 在序列化程序中从同一模型生成两个字段

vsdwdz23  于 2022-12-01  发布在  Go
关注(0)|答案(1)|浏览(120)

我在另一个序列化器中使用嵌套序列化器,并且我有两个模型ObjectObjectMedia,请参见以下代码:

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",
        ]

我想在两个字段中添加对象媒体(由其类型分隔),如下所示,但我不知道如何实现:

{
  "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
    }]
}
gab6jxml

gab6jxml1#

您可以使用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",
        ]

请注意,它们是只读的。此处为官方文档。

相关问题