When we use mongoengine and want to get last item, most of us use as this example.
Users.objects.order_by('-id').first()
I want to use last(), instead of above example. because I think first and last must be paired.
The following code is what I want.
Users.objects.last()
Thank you for your effort, contributors. 馃憤
Hey @devArtoria ! Do you have a real-life use case where you'd use .last()? What made you think it would be useful to have it besides the fact that it logically complements .first()?
It can be used when recalling the most recently registered items, for example, when recalling recent items of transaction data.
in my case, I made simple blockchain implementation and I want to get last block by using last() but I have to flip the index and use first ().
Also as I said before, if you use first () naturally, you might think there will be last (), but it's not intuitive because it does not exist now. In the end, we flip the index and use first (), and this is not intuitive.
Thank you for giving me the answer.
PS. MongoDB also have $last.
So instead of Doc.objects.order_by('-some_field').first() you'd want Doc.objects.order_by('some_field').last()? The latter would have to flip the sort and use findOne again (sidenote: what happens if sort isn't defined?), making it basically equivalent to the former call.
At the moment, I don't see the value of adding another way of doing the same thing. Quoting import this: There should be one-- and preferably only one --obvious way to do it.
MongoDB does have a $last aggregation operator, but that's unrelated.
but I think it's implicit.
so I will quote the following sentence.
"Explicit is better than implicit"
class ExplicitQuerySet(QuerySet):
def last.....
class Doc(Document):
....
meta = {
'queryset_class': ExplicitQuerySet,
}
We could solve with this code without polluting master code.
OK, I agree your solution is the better.
thaks for your advices @erdenezul and @wojcikstefan .
and it seems we can close this issue 馃憤
glad to hear that helped
Most helpful comment
class ExplicitQuerySet(QuerySet): def last..... class Doc(Document): .... meta = { 'queryset_class': ExplicitQuerySet, }We could solve with this code without polluting master code.