Search code examples
jsondjangoujson

Using ujson instead of Django default json serializer


As you known, Django uses json module from Python standard library for serializing querysets to json, and DjangoJSONEncoder class uses json.JSONEncoder as its superclass, and there is no such class in ujson library.

How can I use ujson instead of json in Django serializer?


Solution

  • You can do something like this (using values):

    some_values = SomeModel.objects.values(
            'pk', 'some_field',
    )
    

    and serialising it:

    mark_safe(ujson.dumps(list(some_values), ensure_ascii=False))