How do I turn MongoDB query into a JSON?

后端 未结 4 1966
难免孤独
难免孤独 2021-01-30 08:54
for p in db.collection.find({\"test_set\":\"abc\"}):
    posts.append(p)
thejson = json.dumps({\'results\':posts})
return  HttpResponse(thejson, mimetype=\"application/j         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 09:53

    It's pretty easy to write a custom serializer which copes with the ObjectIds. Django already includes one which handles decimals and dates, so you can extend that:

    from django.core.serializers.json import DjangoJSONEncoder
    from bson import objectid
    
    class MongoAwareEncoder(DjangoJSONEncoder):
        """JSON encoder class that adds support for Mongo objectids."""
        def default(self, o):
            if isinstance(o, objectid.ObjectId):
                return str(o)
            else:
                return super(MongoAwareEncoder, self).default(o)
    

    Now you can just tell json to use your custom serializer:

    thejson = json.dumps({'results':posts}, cls=MongoAwareEncoder)
    

提交回复
热议问题