Reputation: 809
In django how to get latest instance of a query set if i'm using MongoEngine
Normally we do
Users.objects.latest('id')
But i cant use latest
in MongoEngine.
;) . i'm in stuck .
I didn't find a solution here . but i've implemented . whats your opinion about below
Users.objects.all().order_by('-id').limit(1)[0]
This will return the latest instance .
and also fixed the issue by committing it to mongoenngine.
https://github.com/anishmenon/mongoengine/
You may install this and use
Users.objects.latest('id')
Upvotes: 14
Views: 7242
Reputation: 93
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()
Upvotes: 6