Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
snippet = Snippet(code='foo = "bar"\n')
snippet = Snippet(code='print("hello, world")\n')
snippet.save()
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json
.
content = JSONRenderer().render(serializer.data)
content
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'
…then we restore those native datatypes into a fully populated object instance.
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
serializer.save()
# <Snippet: Snippet object>
We can also serialize querysets instead of model instances. To do so we simply add a flag to the serializer arguments.