Search code examples
djangodjango-modelsdjango-viewsdjango-database

How do i get the highest ID of an item within a database in djngo?


When I try to save a new item I need to find the item with the highest ID in the database in order to add 1 to it and save the next item in the order in the database. Simply counting the items in the DB will not work as if an item is deleted the count will be incorrect.

I have no code to fix but pseudo looks something like:

look at all the items in the DB
Find the item with the highest ID 
Add one to that number
save the new item with the new highest id in the DB

I am using Django. as such it should use the querysets within Django and or python.


Solution

  • Field id of the Django Model is by default auto increment so whenever you save a new object to the database it does exactly what you want - saves object with id greater than the last object's id by one.

    Anyways, there are multiple ways you can retrieve latest id from the database. The most efficient way (simplest and fastest database query since you want only id value returned, not the whole object) is by saying:

    latest_id = Model.objects.all().values_list('id', flat=True).order_by('-id').first()
    

    The queryset looks like this:

    SELECT 'model'.'id' FROM 'model' ORDER BY 'model'.'id' DESC  LIMIT 1; 
    

    all() gets all objects of the model from the database, values_list('id', flat=True) extracts only the value of the id field (this saves you time because you don't retrieve all model fields), order_by('-id') orders objects by id in descending order and first() gives you the desired result which is the last id.

    There is also method like last() that does the oposite of method first(). It retrieves last whole object of the model from the database or the method latest('id') which does the same.