假设我有一个模型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
我为我的模型创建了一个Serializer类
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,我希望它是一个Image url数组,是否有可能呢?
答案 0 :(得分: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 _"映射到方法命名惯例
答案 1 :(得分:0)
可以设置depth=1
展开所有相关模型的深度:
class CollectionSerializer(ModelSerializer):
class Meta:
model = Collection
fields = [
'id',
'name',
'description',
'publish',
'author',
'images',
]
depth = 1