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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With