[Fixed]-Mongoengine get latest()

25👍

You could do:

Users.objects.order_by('-id').first()
👤Ross

6👍

Ross’s answer is great enough.

But if you really need a latest(), implementing a custom QuerySet can do this.

“Decorator” way:

class Users(Document):
    username = StringField()

    @queryset_manager
    def latest(doc_cls, queryset):
        return queryset.order_by('-id').first()

“meta” way:

class UsersQuerySet(QuerySet):

    def latest(self):
        return self.order_by('-id').first()

class Users(Document):
    meta = {'queryset_class': UsersQuerySet}

Now you can:

Users.objects.latest()
# or
Users.latest()

Leave a comment