i need to get the most recent data of a table in django but I want the fastest way to do this.
which one is fastest?
foo.objects.latest("id")
foo.objects.last()
or should i use get()
with one of above methods ?
CodePudding user response:
If your Foo
model did not specify an get_latest_by
model option [Django-doc], then the two are equivalent. Indeed, as discussed in my answer on the difference between .last()
and .latest()
:
.first()
and.last()
will work with the ordering of the queryset if there is one,.earliest(…)
and.latest(…)
will omit any.order_by(…)
clause that has already been used;- if the queryset is not ordered
.first()
and.last()
will order by the primary key and return the first/last item of that queryset,.earliest(…)
and.latest(…)
will look for theget_latest_by
model option [Django-doc] if no fields are specified;
If get_latest_by
is thus not specified, or the primary key, both queries will result in a query that looks like:
SELECT * FROM foo ORDER BY id DESC LIMIT 1
Both methods are not equivalent, but in this case will produce the same query, and thus have the same impact on the database.
or should i use
get()
with one of above methods?
No, .last
and .latest()
are eager methods, they will directly make the query and return a Foo
object (or None
), it thus does not make sense to call .get()
since a model has no .get()
method defined on it.