0

[EDITED]

I have any api using flask + connexion (swagger 2.0)

Any time I retrieve a collection from the database, using simple code such as:

# GET /api/model
def get_all_model():
    return Model.objects

I get the following error:

TypeError: [Model] is not JSON serializable

As a workaround, I have done the following

def get_all_model():
    return json.loads(model.objects.to_json())

How can I return the entire collection without serializing/deserializing?

from the docs:

Document classes have an objects attribute, which is used for accessing the objects in the database associated with the class. The objects attribute is actually a QuerySetManager, which creates and returns a new QuerySet object on access. The QuerySet object may be iterated over to fetch documents from the database:

Felipe
  • 10,606
  • 5
  • 40
  • 57

1 Answers1

1

The question is clear now. I think there is no way to return a list instead of queryset to serialize it directly to JSON. Though, you should do it yourself by iterating over all documents (using queryset object) and putting them in a list of dictionaries. I recommend doing something like this:

import mongoengine

mongoengine.connect('mongoenginetest', host='mongomock://localhost')

class Student(mongoengine.Document):
    name = mongoengine.StringField()

    @mongoengine.queryset_manager
    def serialized_objects(doc_cls, queryset):
        return [{'name': doc.name} for doc in queryset]

student1 = Student(name='John')
student1.save()

print(type(Student.serialized_objects))  # prints <class 'list'>
print(Student.serialized_objects)  # prints [{'name': 'John'}]

You can rename serialized_objects to objects. Also, look at this page:https://gist.github.com/benwah/3009143

Happy day!

Aliakbar Abbasi
  • 209
  • 1
  • 10
  • I've edited the question to be more clear. I am trying to avoid having to serialize and then deserialize because it is unnecessary work being done. There should be a way to get the items as a python dictionary? I thought `as_pymongo()` would do this, but it does not appear to be the case – Felipe Sep 20 '17 at 21:18