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')
MongoEngine provides the following methods for atomic updates on a queryset. update_one() − Overwrites or adds first document matched by query. update() − Performs atomic update on fields matched by query. modify() − Update a document and return it.
Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.
PyMongo is the low-level driver wrapping the MongoDB API into Python and delivering JSON in and out. MongoEngine or other layers like MongoKit map your MongoDB-based data to objects similar to native Python database drivers + SQLAlchemy as ORM.
You could do:
Users.objects.order_by('-id').first()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With