Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework serializer losing data

In my unittests, and in reality, the ModelSerializer class I've created just seems to discard a whole trove of data it is provided with:

class KeyboardSerializer(serializers.ModelSerializer):
    user = serializers.Field(source='user.username')
    mappings = KeyMapSerializer(many=True, source='*')

    class Meta:
        model = Keyboard
        fields = ('user', 'label', 'is_primary', 'created', 'last_modified', 'mappings')

    def pre_save(self, obj):
        obj.user = self.request.user

TEST_KEYBOARD_MAP = {
                        'user': None,
                        'label': 'New',
                        'is_primary': True,
                        'created': '2013-10-22T12:15:05.118Z',
                        'last_modified': '2013-10-22T12:15:05.118Z',
                        'mappings': [
                            {'cellid': 1, 'key': 'q'},
                            {'cellid': 2, 'key': 'w'},
                        ]
}

class SerializerTests(TestCase):

    def setUp(self):
        self.data = TEST_KEYBOARD_MAP

    def test_create(self):
        serializer = KeyboardSerializer(data=self.data)
        print serializer.data

Output:

{'user': u'', 'label': u'', 'is_primary': False, 'created': None, 'last_modified': None, 'mappings': {'id': u'', 'cellid': None, 'key': u''}}

What is happening to all the information passed in to the serializer in data?

like image 370
jvc26 Avatar asked Oct 03 '22 15:10

jvc26


1 Answers

The data key is not populated until you call is_valid(). (This is a data-sanitation safety feature that stops you accessing input until you're sure it's safe.

Add the call to is_valid() and you should see your data.

Since you're deserializing though you want to access the object attribute to return you Keyboard instance.

If you review the DRF docs on deserializing objects they show exactly the example you need:

serializer = CommentSerializer(data=data)
serializer.is_valid()
# True
serializer.object
# <Comment object at 0x10633b2d0>

I hope that helps.

like image 176
Carlton Gibson Avatar answered Oct 05 '22 04:10

Carlton Gibson