django rest框架将id更改为url

django rest框架将id更改为url,django,django-rest-framework,Django,Django Rest Framework,假设我有一个模型Collection,与CollectionImage class Collection(models.Model): name = models.CharField(max_length=500) description = models.TextField(max_length=5000) publish = models.DateTimeField(auto_now=False, auto_now_add=True) author = mod

假设我有一个模型
Collection
,与
CollectionImage

class Collection(models.Model):
    name = models.CharField(max_length=500)
    description = models.TextField(max_length=5000)
    publish = models.DateTimeField(auto_now=False, auto_now_add=True)
    author = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class CollectionImage(models.Model):
    collection = models.ForeignKey('Collection', related_name='images')
    image = models.ImageField(height_field='height_field', width_field='width_field')
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)

    def __str__(self):
        return self.collection.name
我为我的模型创建了一个序列化器类

class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]
和API视图

class CollectionList(ListAPIView):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer

我遇到的问题是,字段图像提供了一个ID数组,我希望它是一个图像URL数组,可以这样做吗?

是的,DRF非常灵活,可以支持这一点。我建议对此功能使用SerializerMethodField。它本质上允许您将序列化程序字段映射到自定义函数的结果

您的实现如下所示:

class CollectionSerializer(ModelSerializer):
    images = serializers.SerializerMethodField()

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]

    def get_images(self, obj):
        return [collection_image.image.url for collection_image in obj.images]
资料来源:


**该字段通过“获取”命名约定映射到方法

可以设置
depth=1
将所有相关模型展开一层:

class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]
        depth = 1