Search code examples
pythonflask-mongoengine

How to iterate over a query result Flask-Mongoengine if the cursor doesn't support list slices


I am making a todo list app and i want to reverse the list that the query returns because I want the most recent todo item on top the error I am getting is
IndexError: Cursor instances do not support slice steps
this is my code:

def index():
    todos = Todo.objects.all()
    todos = todos[::-1]
    return render_template('index.html', todo=todos)

Solution

  • Do you have a datetime field? If you are sorting by the _id, you will sort by the insertion time. This basically means that the comparison is not done on just the timestamp portion.. Assuming you have a date field then something like this would use order_by to sort the result set.

    order_by takes a variable number of string arguments, which are the field names (as defined in your documents) optionally preceded by a "-" (to indicate a descending sort, i.e. highest first).

    def index():
        todos = Todo.objects().order_by('-datetimeFieldOfYourTodoCreation')
        return render_template('index.html', todo=todos)