【问题标题】:django rest framework changing id to urldjango rest框架将id更改为url
【发布时间】:2017-04-02 21:03:00
【问题描述】:

假设,我有一个模型 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 数组,有可能吗?

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    是的,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]
    

    来源: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-07-19
        • 2021-01-17
        • 2015-06-06
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 2022-08-03
        • 2019-10-29
        • 1970-01-01
        相关资源
        最近更新 更多