Django Rest Framework TypeError at / __init__() 得到关键字参数 'read_only' 的多个值

Django Rest Framework TypeError at / __init__() got multiple values for keyword argument 'read_only'

这个超级有用的错误“ATypeError at / init() 为关键字参数 'read_only' 获取了多个值”发生在以下序列化程序中

class UserSerializer(serializers.ModelSerializer):
    posts = serializers.HyperlinkedIdentityField('posts', lookup_field='username', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'posts', )


class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(required=False,  read_only=True)
    photos = serializers.HyperlinkedIdentityField('photos', read_only=True)
    # author = serializers.HyperlinkedRelatedField(view_name='user-detail', lookup_field='username')

    def get_validation_exclusions(self, *args, **kwargs):
        # Need to exclude `user` since we'll add that later based off the request
        exclusions = super(PostSerializer, self).get_validation_exclusions(*args, **kwargs)
        return exclusions + ['author']

    class Meta:
        model = Post


class PhotoSerializer(serializers.ModelSerializer):
    image = serializers.Field('image.url' , read_only=True)


    class Meta:
        model = Photo

有什么帮助吗?

字段 HyperlinkedIdentityField 始终是只读的,这就是它不支持 read_only 参数的原因。允许的参数:

  • view_name
  • lookup_field
  • lookup_url_kwarg
  • 格式