0

Just as title described.When we have a mongoengine model as below: class Model(Document): some fields definition~~ And I added some items to the database by the Model, when I want to traversal all items, there are three ways, and which should I use? The first: for model in Model.objects: do something to model~~

The second: for model in Model.objects(): do something to model~~

The third: for model in Model.objects.all(): do something to model~~

It seems that the three ways performed the same~~

Community
  • 1
  • 1
zhangqy
  • 853
  • 7
  • 10

1 Answers1

0

Good question! This is my opinion:

All of them are similar when you want to get all documents in a collection. All of them return a queryset that you can iterate on it. But, if you want to filter the result, you should use objects(). Like this:

for model in Model.objects(first_name='John', last_name='Doe'):
    do something to model~~

The ojbects.all() is pretty use-less in my opinion and is added to completeness because there is a symmetric objects.first() method. Maybe in some conditions, using objects.all() is explicit and more readable.

If you want to get a range of documents you can use array-slicing syntax with objects that looks really good and readable.

for model in Model.objects[10:20]:
    do something to model~~

Without using array-slicing syntax with objects, it is a real pain to determine a range:

for model in Model.objects().skip(10).limit(20):  # not recommended
    do something to model~~

In essence, objects.all() is use-less or used for readability, objects is good for getting all documents and or a range of documents and objects() is good for restricting the returned documents with some filters.

Have a good day!

Aliakbar Abbasi
  • 209
  • 1
  • 10