在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可序列化的
答案 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