tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

Last inserted row method

Open Nenrikido opened this issue 5 years ago • 5 comments

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

Nenrikido avatar May 05 '20 08:05 Nenrikido

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.

hqsz avatar May 13 '20 14:05 hqsz

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.

grigi avatar May 13 '20 14:05 grigi

If we don't have a default ordering, we will likely raise an exception saying we need an ordering to reverse.

grigi avatar May 13 '20 14:05 grigi

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.

WisdomPill avatar Feb 08 '21 10:02 WisdomPill

You mean a .latest() method? How is Table.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

andcan86 avatar Mar 10 '22 10:03 andcan86