Django REST框架 - serializer.is_valid()丢失数据

时间:2016-04-18 00:24:29

标签: python django serialization django-rest-framework django-serializer

我在使用Django REST Framework序列化程序时遇到了一些问题(是的,我是Django noob)。 特别是,在serializer.is_valid()调用之后,一些数据会丢失':

    serializer = ReviewSerializer(data=request.data, many=False)
    print serializer
    if not serializer.is_valid():
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    print serializer.validated_data

这是输出:

ReviewSerializer(data={u'album': {u'spotify_id': 1, u'name': u'TEXT'},
   u'rating': 1, u'artistImage': {u'url': u'ARTIST_URL'}, u'artist': 
  {u'genres': u'ROCK', u'spotify_id': 1, u'name': u'TEXT'}, 
   u'review': u'TEXT', u'albumImage': {u'url': u'ALBUM_URL'}}):

review = CharField(max_length=None)
rating = DecimalField(decimal_places=1, max_digits=2)
artist = ArtistSerializer():
    name = CharField(max_length=100)
    genres = CharField(max_length=100)
    spotify_id = CharField(max_length=50)
album = AlbumSerializer():
    name = CharField(max_length=100)
    spotify_id = CharField(max_length=50)
artistImage = ArtistImageSerializer()
albumImage = AlbumImageSerializer()


OrderedDict([(u'review', u'TEXT'), (u'rating', Decimal('1')), 
  (u'artist', OrderedDict([(u'name', u'TEXT'), (u'genres', u'ROCK'), 
  (u'spotify_id', u'1')])), (u'album', OrderedDict([(u'name', u'TEXT'), 
  (u'spotify_id', u'1')])), (u'artistImage', OrderedDict()),    
  (u'albumImage', OrderedDict())])

特别是,fieldImage和albumImage字段都是空的OrderedDict。 以下是序列化器:

class ReviewSerializer(serializers.Serializer):

  review = serializers.CharField(max_length=None)
  rating = serializers.DecimalField(decimal_places=1, max_digits=2)
  artist = ArtistSerializer()
  album = AlbumSerializer()
  artistImage = ArtistImageSerializer()
  albumImage = AlbumImageSerializer()

class AlbumImageSerializer(serializers.ModelSerializer):

  class Meta:
    model = ArtistImage
    fields = ('url')

class ArtistImageSerializer(serializers.ModelSerializer):

  class Meta:
    model = ArtistImage
    fields = ('url')

此外,我注意到如果我删除序列化程序打印,在验证之前,我收到错误:

    serializer = ReviewSerializer(data=request.data, many=False)
    if not serializer.is_valid():
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    print serializer.validated_data

Traceback (most recent call last):
...
TypeError: The `fields` option must be a list or tuple or "__all__". Got str.

1 个答案:

答案 0 :(得分:1)

您可以尝试更换

吗?
fields = ('url')

fields = ('url',)

括号不会自动使它们成为元组。你必须在字符串后面添加一个逗号来向python表明它应该是一个元组。

来自Docs

  

一个特殊问题是构造包含0或1的元组   items:语法有一些额外的怪癖来容纳这些。空   元组是由一对空括号构成的;一个元组   通过使用逗号跟随值来构造一个项目(它不是   足以将一个值括在括号中)。丑,但是   有效的。