CountryField empty value json serialization vs 3.0

963 views
Skip to first unread message

Zoltan Szalai

unread,
Dec 2, 2014, 9:48:25 AM12/2/14
to django-res...@googlegroups.com
Hi,

First of all, huge thanks for 3.0! I've decided to migrate my latest
project to get a sense of it. One issue I ran into is with CountryField
from django-countries.
If the value is empty, 3.0 raises a "TypeError: Country(code=u'') is not
JSON serializable" exception. Checking out the 'to_representation'
method of ChoiceField makes it obvious why: Country(code=u'') is not in
('', None) and '' is not a key in the choices list and since 'Country' a
custom object it's not json serializable by default.

Putting something like:

if unicode(value) == '':
return ''

to the beginning of 'to_representation' would fix it but something
suggests it's not a great idea.

So what to do you think is the best way to solve this in 3.0 without
using custom serializer fields?

thanks
Zoltan

Tom Christie

unread,
Dec 2, 2014, 12:08:29 PM12/2/14
to django-res...@googlegroups.com
The easiest way to deal with it would just be to create a custom field to deal with mapping it to a sensible output representation.

It would be interesting to know *why/how* this was able to work in 2.x tho'.

It's not impossible there's some subtle difference and that in 2.x it was using `serializers.ModelField` but is not using `serializers.ChoiceField` - not sure?...

Vlad Lep

unread,
Apr 21, 2015, 2:57:34 PM4/21/15
to django-res...@googlegroups.com
Hi,

I had the same problem. I wrote a custom field  for the CountryField, as suggested, and overwrote the to_representation method. It works so thanks for the post.

I was curious if you found a different solution in the end? I use the country field in several models and would like to have it nicely done. 

Thanks,
Vlad

Daviddd

unread,
May 22, 2015, 10:55:00 AM5/22/15
to django-res...@googlegroups.com
I have the same issue and I found this on github:
"Field is not serializeable with Django Rest Framework"
Reply all
Reply to author
Forward
0 new messages