Django Rest Framework Dictionary Field

I am using Mongodb with mongoengine as the backend for the API in Django. The structure I use to create the api is the Django Rest Framework.

I need to save the dictionary in a field in Mongo, and the best I did when the post method is called is to use charfield and parse the dictionary in restore_object function.

Is there a better way to achieve this?

Better create a dict field? I don’t know how hard it is.

Thanks.

edited to show some code, note that I store the dictionary as a dict (DictField), and the contents may change from one object to another.

my mongoengine model looks something like this:

class MyDoc(mongoengine.Document): name = mongoengine.StringField(max_length=200) context = mongoengine.DictField() 

and my serializer is something like:

 class MyDocSerializer(serializers.Serializer): name = serializers.CharField(max_length=200) context = serializers.CharField() url = serializers.HyperlinkedIdentityField( view_name="drf:mydoc-detail",) def __init__(self,*args,**kwargs): super(MyDocSerializer,self).__init__(*args,**kwargs) def restore_object(self, attrs, instance=None): #Parse string to dict #this is so ugly, notice I had to repace ' for " to #avoid an error parsing the json context = JSONParser().parse( StringIO.StringIO( attrs['context'].replace("'","\"") ) ) attrs['context'] = context if instance is not None: instance.name = attrs['name'] instance.context = context return instance return MyDoc(**attrs) 
+6
source share
1 answer

Instead of processing the dictionary field in the restore_object Serializer, you will probably get something a little cleaner if you instead use a custom field for the dictionary field that controls the conversion between the dictionary view and the inner char.

You will need to subclass serializers.WritableField and override the to_native() and from_native .

Relevant documents here .


Note. The WritableField class, which was present in version 2.x, no longer exists. You must subclass the field and override to_internal_value () if the field supports data entry.


Update . Starting with version 3.0.4 you can use serializers.DictField ... http://www.django-rest-framework.org/api-guide/fields/#dictfield

+6
source

All Articles