Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last record in a queryset

How can I retrieve the last record in a certain queryset?

like image 537
Stephen Avatar asked Feb 03 '10 09:02

Stephen


People also ask

How do I get latest data in Django?

You need to specify a field in latest(). eg. Or if your model's Meta specifies get_latest_by, you can leave off the field_name argument to earliest() or latest() . Django will use the field specified in get_latest_by by default.

Can you filter a QuerySet?

Yes, you can reuse existing querysets. This is not really making anything faster though, in fact, this code block won't even execute a query against the database because Django QuerySets are lazily evaluated. What I means is that it won't send the query to the database until you actually need the values.

What is first () in Django?

In my last Django project, we had a set of helper functions that we used a lot. The most used was helpers. first, which takes a query set and returns the first element, or None if the query set was empty. Instead of writing this: try: object = MyModel.objects.get(key=value) except model.DoesNotExist: object = None.


1 Answers

Django Doc:

latest(field_name=None) returns the latest object in the table, by date, using the field_name provided as the date field.

This example returns the latest Entry in the table, according to the pub_date field:

Entry.objects.latest('pub_date') 
like image 97
Asinox Avatar answered Sep 18 '22 15:09

Asinox