brianjbuck/drf_orjson_renderer

Render problem

Closed this issue · 3 comments

Lazy project objects such as lazy translations are not rendered properly. They are not actual strings and have iter method, so rederer renders them as list of chars

I stumbled onto the same problem when wanting to use the renderer.

I fixed it by overriding the renderer, short example here.

from django.utils.functional import Promise
from drf_orjson_renderer.renderers import ORJSONRenderer as OriginalORJSONRenderer

class ORJSONRenderer(OriginalORJSONRenderer):
    @staticmethod
    def default(obj):
        # resolve promises/lazy values if needed
        if isinstance(obj, Promise):
            # django does it the same way internally,
            # for example in the main `get_prep_value`
            # impl for fields
            obj = obj._proxy____cast()

        return OriginalORJSONRenderer.default(obj)

It's using a private method, so could break anytime.

if @brianjbuck is fine with that approach, I also would be happy to provide a PR for this.

Also, I just saw the default DjangoJSONEncoder is doing:

elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
    return str(o)

see here

@syphar, Yes create a PR and I'll create a new release. Thanks for the assist 🙌