如何序列化 Cloudinary 字段?

问题描述 投票:0回答:1

我正在尝试使用适用于 Svelte 和 Django 的 Cloudinary SDK。我有一个模型

CloudinaryField
:

class Room(models.Model):
    ...
    avatar = CloudinaryField("image")

class UserRoom(models.Model):
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    ...

UserRoom
:

的序列化器
class UserRoomSerializer(ModelSerializer):
    user = UserSerializer()
    last_message = SerializerMethodField()

    def get_last_message(self, obj):
        return MessageSerializer(obj.room.message_set.first()).data

    class Meta:
        model = UserRoom
        fields = "__all__"
        depth = 1

我想使用 Cloudinary 的 svelte 组件

<CldImage />
并且我需要将图像公共 id 传递给它。但是当我发出请求时,我得到的是图像路径,而不是 id:

{
  "id": 1,
  "user": {
    ...
  },
  "last_message": {
    ...
  },
  "unread_messages": 0,
  "room": {
    "id": "49c33134-cc9f-43e0-b524-b05e9387602d",
    "name": "test",
    "avatar": "image/upload/v1728304120/sz8h5f5oqbtc95cfxbvx.jpg" // THIS LINE IS A PATH, NOT AN ID
  }
}

如何让 DRF 发送 id,而不是路径?

django django-rest-framework cloudinary
1个回答
0
投票

发生这种情况的原因是因为

CloudinaryField
没有用于 Django REST 框架 (DRF) [drf-doc] 的专用字段。这意味着它将尝试调用相应字段的
.value_to_string(…)
方法[GitHub]
,该方法返回路径。

我们可以定义一个自定义序列化器,它采用

.public_id
CloudinaryResource
:

class RoomSerializer(ModelSerializer):
    avatar = models.CharField(source='avatar.public_id', read_only=True)

    class Meta:
        model = Room
        fields = '__all__'


class UserRoomSerializer(ModelSerializer):
    user = UserSerializer()
    last_message = SerializerMethodField()
    room = RoomSerializer()

    def get_last_message(self, obj):
        return MessageSerializer(obj.room.message_set.first()).data

    class Meta:
        model = UserRoom
        fields = '__all__'
        depth = 1
© www.soinside.com 2019 - 2024. All rights reserved.