1

I was hoping somebody could advise my on this: my serializer returns an empty string, despite the data being correct.

def foo(self, request, uuid=None):
        data = JSONParser().parse(request)
        logger.error(data)
        serializer = MySerializer(data=data)
        logger.error(serializer.data) #Empty JSON string 
        something.bar(serializer.data, self.request.user)
        return Response(status=status.HTTP_201_CREATED)

MySerializer:

class MySerializer(serializers.Serializer):

    foo1 = serializers.BooleanField()
    foo2 = serializers.CharField(max_length=200, required=True)
    foo3 = serializers.BooleanField()

    class Meta:
        fields = ('foo1',
                  'foo2',
                  'foo3')

The data returned by the serializer from serializer.data: foo1: '', foo2: False, foo3: False

Where am I going wrong?

2 Answers 2

3

I believe your answer comes directly from rest_framework/serializers.py:

@property
def data(self):
    if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'):
        msg = (
            'When a serializer is passed a `data` keyword argument you '
            'must call `.is_valid()` before attempting to access the '
            'serialized `.data` representation.\n'
            'You should either call `.is_valid()` first, '
            'or access `.initial_data` instead.'
        )
        raise AssertionError(msg)
Sign up to request clarification or add additional context in comments.

Comments

2

You need to call .is_valid() on the serializer first with the data and then access the serialized data(which Joey also pointed out).

def foo(self, request, uuid=None):
    data = JSONParser().parse(request)
    logger.error(data)
    serializer = MySerializer(data=data)
    serializer.is_valid(raise_exception=True) # explicitly call .is_valid() first 
    logger.error(serializer.data) #Empty JSON string  
    something.bar(serializer.data, self.request.user)
    return Response(status=status.HTTP_201_CREATED)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.