在Django Rest Framework中,如何将值序列化为arraylist?

时间:2015-12-04 03:17:20

标签: json django django-rest-framework

在Django Rest Framework 3.0 +中,我希望得到这个值:

{
  image:[img1,img2,img3]
}

我的代码如下:

models.py

class UserDynamic(models.Model):

    """User dynamic"""
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    content = models.TextField(max_length=200)
    createtime = models.DateTimeField(auto_now_add=True)


class UserDynamicImage(models.Model):

    """User dynamic images"""
    userdynamic = models.ForeignKey(UserDynamic)
    image = models.ImageField(upload_to='UserDynamicImage/')

serializers.py

class UserDynamicImageSerializer(serializers.ModelSerializer):  
    def to_representation(self, obj):
        return obj.image

class UserDynamicSerializer(serializers.ModelSerializer):

    user = UserProfileSerializer()
    imgs = serializers.SerializerMethodField('GetImage')
    # imgs = serializers.ListField(img = serializers.ImageField())
    # imgs = UserDynamicImageSerializer(many=True, read_only=True)

    class Meta:
        model = UserDynamic
        fields = ('id', 'user', 'content', 'imgs', 'createtime')

    def GetImage(self,UserDynamic):
        entity = UserDynamicImage.objects.filter(userdynamic = UserDynamic)
        return UserDynamicImageSerializer(entity,many=True,context={"request": self.context['request']}).data

现在,它返回一个错误:  不是JSON可序列化的

1 个答案:

答案 0 :(得分:0)

UserDynamicImageSerializer而不是返回obj.image返回obj.image.url

你可以这样做:

class UserDynamicImageSerializer(serializers.ModelSerializer):  
    def to_representation(self, obj):
        if obj.image:
            return obj.image.url

在不使用UserDynamicImageSerializer的情况下执行此操作的另一种方法:

class UserDynamicSerializer(serializers.ModelSerializer):

    user = UserProfileSerializer()
    imgs = serializers.SerializerMethodField('GetImage')

    class Meta:
        model = UserDynamic
        fields = ('id', 'user', 'content', 'imgs', 'createtime')

    def GetImage(self,UserDynamic):
        entity = UserDynamicImage.objects.filter(userdynamic=UserDynamic).values_list('image',flat=True)
        return entity