db.models.query.QuerySet.latest()

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')

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.

Like get(), earliest() and latest() raise DoesNotExist if there is no object with the given parameters.

Note that earliest() and latest() exist purely for convenience and readability.

earliest() and latest() may return instances with null dates.

Since ordering is delegated to the database, results on fields that allow null values may be ordered differently if you use different databases. For example, PostgreSQL and MySQL sort null values as if they are higher than non-null values, while SQLite does the opposite.

You may want to filter out null values:

Entry.objects.filter(pub_date__isnull=False).latest('pub_date')
doc_Django
2016-10-09 18:36:13
Comments
Leave a Comment

Please login to continue.