2

I am using Pymodm as a mongoDB odm with python flask. I have looked through code and documentation (https://github.com/mongodb/pymodm and http://pymodm.readthedocs.io/en/latest) but could not find what I was looking for.

I am looking for an easy way to fetch data from the database without converting it to a pymodm object but as plain JSON. Is this possible with pymodm?

Currently, I am overloading the flask JSONEncoder to handle DateTime and ObjectID and use that to convert the pymodm Object to JSON.

Evhz
  • 8,852
  • 9
  • 51
  • 69
Jodo
  • 4,515
  • 6
  • 38
  • 50

3 Answers3

2

It is not obvious from the PyMODM documentation, but here's how to do it:

pymodm_obj.to_son().to_dict()

Actually, I just re-read your question, and I don't think anything is forcing you to use PyMODM everywhere in your project once you have made the decision to use it. So if you are just looking for the JSON structures, you could just use the base pymongo package functionality.

J.Makela
  • 1,034
  • 9
  • 9
1

Having:

from pymodm import MongoModel, fields
import json

class Foo(MongoModel):
  name = fields.CharField(required=True)

a=Foo()

You can do:

jsonFooString=json.dumps(a.to_son().to_dict())
Evhz
  • 8,852
  • 9
  • 51
  • 69
  • Thats what I had beforehand. As I stated in my question I am overloading the JSONEncoder to handle the special fields. In the end, it worked quite well actually and its a good enough solution for me. – Jodo Apr 06 '18 at 10:51
  • It's kind of a lack that `pymodm` has not a direct way to export an object to json, which could handle properly, for example, the `ObjectId()` fields – Evhz Apr 06 '18 at 13:20
-1

If you need to build CRUD api you might also want to check this little package, basically DRF for pymodm

So if you want to create CREATE/UPDATE/DELETE it would look like this

from api.pymodm_rest import viewsets

class ServiceAreaViewSet(viewsets.ModelViewSet):
    queryset = ServiceArea.objects
    instance_class = ServiceArea
    lookup_field = '_id'

[https://github.com/lokoArt/pymodm_rest][1]

James
  • 523
  • 4
  • 19