Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.

    1. from snippets.serializers import SnippetSerializer
    2. from rest_framework.renderers import JSONRenderer
    3. from rest_framework.parsers import JSONParser
    4. snippet = Snippet(code='foo = "bar"\n')
    5. snippet = Snippet(code='print("hello, world")\n')
    6. 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.

    1. content = JSONRenderer().render(serializer.data)
    2. content
    3. # 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.

    1. serializer.is_valid()
    2. # True
    3. serializer.validated_data
    4. # OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
    5. serializer.save()
    6. # <Snippet: Snippet object>

    We can also serialize querysets instead of model instances. To do so we simply add a flag to the serializer arguments.