添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
威武的葡萄酒  ·  JS常见加密 ...·  1 年前    · 
耍酷的柳树  ·  @azure/openai - npm·  2 年前    · 
Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more

I'm using Mongodb with mongoengine as a backend for a API in Django. The framework I'm using to create the api is Django Rest Framework.

I need to store a dictionary in a field in Mongo and the best I've done when the method post is called is to use a charfield and parse the dictionary in the function restore_object.

There is a better way to achieve this goal?

It's better to create a dict field? I don't know how hard this could be.

Thank you.

edited to show some code, notice that I store the dictionary as a dict (DictField) and it's content could change from one object to other.

my mongoengine model is something like:

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

and my serializer 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)
                could you post your document definitions and some code? i think it would be helpful
– dm03514
                Jan 31 '13 at 15:00
                You could use the pymongo serializers - see: api.mongodb.org/python/current/api/bson/json_util.html
– Ross
                Jan 31 '13 at 21:34
                In 2016 you can use Django-REST-Framework-Mongoengine (github.com/umutbozkurt/django-rest-framework-mongoengine), which provides serializers for your Mongoengine Documents out of the box.
– Boris Burkov
                Sep 12 '16 at 17:26

Rather than deal with the dictionary field in the Serializer's restore_object, you'll probably end up with something slightly cleaner, if instead you use a custom field for the dictionary field, that manages converting between the dictionary representation and internal char based storage.

You'll want to subclass serializers.WritableField and override the to_native() and from_native methods.

Relevant docs here.

Note: WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input.

Update: As of 3.0.4 you can now use serializers.DictField... http://www.django-rest-framework.org/api-guide/fields/#dictfield

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.