0
votes
import mongoengine

class MyLog(mongoengine.EmbeddedDocument):
    text = mongoengine.StringField()

class Server(mongoengine.DynamicDocument):
    name = mongoengine.StringField()
    status = mongoengine.StringField()
    text_list = mongoengine.ListField(mongoengine.EmbeddedDocumentField(MyLog))

Server.objects.all() queryset doesn't include text_list field's value by default. I've to do this- (to get text_list field's value for each object in queryset.

for s in Server.objects.all():
    print s.text_list

In my case/scenario, I can't do this, I mean I have to get all data in a queryset itself(or in other words, I need to have a queryset which will give me the all nested details as well without using obj.text_list)

for e.g.

Further in mongo shell - db.server.find() includes all the nested embedded documents.

{ 
  '_id': ObjectId("272742942qbe5451b4f4b9e7"),
  'name':'nm',
  'status': 'st',
  'text_list': [
       {# here it's including embedded model's info too, no need to make extra query, looking for similar query in mongoengine orm
         'text': 'done'
      }
  ]
}

how can we do this in mongoengine using orm or raw_query.

I can solve this problem in mongoengine orm by using to_json() method

json.loads(queryset.to_json())

Server.objects.all().to_json() returns a result which include embedded models's info but this is not efficient when using pagination on millions documents, I mean in that case mongo will try to convert all objects to to_json.

1
please clarify the question. first you say that the result is not included then you say that you can access the result through an instance attribute. - lesingerouge
@lesingerouge: updated question details. - Wendy
Like @lesingerouge says, it is unclear what you want. The queryset does return the document with its embedded fields you can access as instance attributes. What else? - Jérôme

1 Answers

0
votes

If you want to paginate the results of your queryset using flask-mongoengine, you should simply use the paginate method of the Queryset:

# Paginate through todo
def view_todos(page=1):
    paginated_todos = Todo.objects.paginate(page=page, per_page=10)

Here you can find more info about the templating part and other functions available.