Proxy Object are not serializable

942 views
Skip to first unread message

Matteo Suppo

unread,
Mar 15, 2013, 6:31:13 AM3/15/13
to django-res...@googlegroups.com
I thought it could be a nice idea to provide the Choices of a field with the api. Something like that:

{
  "kind": "first-type",
  "kind_choices": {
    "first-type": "First",
    "second-type": "Second"
  }
}

But my Model Choices are translatable:

Model(models.Model):
  KIND = (("first-type", _("Translate First"), ("second-type", _("Translate Second")

and when I try to put in the serializer

Serializer(serializers.HyperLinkedModelSerializer):
  kind_choices = serializers.Field(source="KIND")

it dies with the error 

<django.utils.functional.__proxy__ object at 0x7fac6c074290> is not JSON serializable

It means of course that the  JSON serializer doesn't call the unicode method on the translatable fields.

With a custom method on the serializer I managed to solve this in a rather crude way:

    def get_kind_choices(self, obj):
        render = {}
        for key, value in obj.KIND:
            render[key] = unicode(value)
        return render

I have a couple question:

1. Is it a good idea to provide the possible Choices through the api? There's a better way to do it?
2. Provided the first question is "Yes, you are doing fine, good job!". What's the best approach to solve this? Should I subclass the JSON Renderer? Create a Custom Field? Is it worth creating a patch to fix the JSONRenderer itself?

Thanks for your time!

Tom Christie

unread,
Mar 18, 2013, 8:04:50 AM3/18/13
to django-res...@googlegroups.com
Hi Matteo,

  I think the right way to resolve this would be to ensure lazily translated string get translated by the serializer field.
It looks to me like we'd want the use of `smart_text`, to instead be `force_text`


Getting this done would involve writing a few tests to ensure everything works as expected, and
a little bit of making sure that the implementation properly covers all the currently support versions of Django.

Feel free to open a ticket against this.  If you'd be up for helping make it happen, that'd be even better. :)

Regards,

  Tom 

Matteo Suppo

unread,
Mar 18, 2013, 8:32:06 AM3/18/13
to django-res...@googlegroups.com
Sure, I could help writing the tests. I'll open a ticket as soon as I will be able to
--
You received this message because you are subscribed to a topic in the Google Groups "django-rest-framework" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-rest-framework/6qrr4iVgIrw/unsubscribe?hl=en.
To unsubscribe from this group and all its topics, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 


--
Matteo Suppo - Social Media Badass

"C'è sempre un altro modo"
"Ho l'80% di probabilità di fare qualsiasi cosa"

Reply all
Reply to author
Forward
0 new messages