Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the latest record with filter in Django

People also ask

How do I get the latest record 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.

How do I filter records in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How can I filter a Django query with a list of values?

To filter a Python Django query with a list of values, we can use the filter method with in . to search Blog entries with pk set to 1,4 or 7 by calling Blog. objects. filter with the pk_in argument set to [1, 4, 7] .


See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest

You need to specify a field in latest(). eg.

obj= Model.objects.filter(testfield=12).latest('testfield')

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.


obj= Model.objects.filter(testfield=12).order_by('-id')[0]

last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')

latest is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting the get_latest_by meta attribute, as mentioned here.


obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution


You can do comparison with this down here.

image

latest('created') is same as order_by('-created').first() Please correct me if I am wrong