Last inserted row method
Describe the solution you'd like Having a clear method to get the last inserted row, useful when you want to use last inserted row at a place where you don't have access to the insertion return
Describe alternatives you've considered
The only alternatives right now are :
Table.all().order_by("-id").first() -> QuerySetSingle
Table.all().order_by("-id").limit(1) -> QuerySet
You mean like latest api in django orm? See link. It just look aliasing of your alternatives : Table.all().order_by("-id").limit(1) If so, I don't think it's urgent.
You mean a .latest() method?
How is Table.all().order_by("-id").first() not adequate?
This would work for autonumber PK, but not UUID's or other custom PK's. In which case you might want to order by a different field (e.g. timestamp?)
So this isn't as easy as one would think?
We could make this use the default sort order for those cases?
Or a datetime field with auto_now=True?
As @lntuition mentioned this isn't trivial, but I see it as a valid case.
If we don't have a default ordering, we will likely raise an exception saying we need an ordering to reverse.
Hello,
I think @Nenrikido meant .last() which is the opposite of .first(). Have a look (here)[https://docs.djangoproject.com/en/3.0/ref/models/querysets/#last].
In my opinion it is a just a convenience method like .first() is, but very useful, especially during testing.
I agree with @grigi, there should be a warning when no default ordering is specified and neither order_by has been called.
You mean a
.latest()method? How isTable.all().order_by("-id").first()not adequate?
I guess everybody thinks that this downloads all the data and does the processing locally. I just tried and it does not (to my surprise).. so it is a fine solution but I would never have guessed that it was a viable option