Latest id of db table OR how to get self.id when saving a new object

Hello everyone,

I want to get latest id of table. Below code is not working if I delete a row from table. For example;

Table
1 firstRow
2 secondRow
3 thirdRow

When I delete thirdRow and call below code; it returns 2. But in reality, it must be 3 because the new sample I will add is saved to the db as the 4th row.

I just want to create a new sample row which includes index_sample column and that column holds current id of row.

How I can solve that? Thank you in advance.

latest_id = Samples.objects.latest('id').id
cycle = Samples.objects.filter(patientid = request.POST.get('p_id'));
if check is '':
   for firstItem in cycle:
       Samples.objects.filter(id=firstItem.id).update(is_index_sample='No', index_sample=latest_id+1);
    sample.is_index_sample = request.POST.get('is_index_sample');
    sample.index_sample = latest_id + 1;

sample.save()

You would actually need to be a bit more precise as to what you’re looking to retrieve here.

You don’t know what PK is going to be assigned at any time, and it’s an extremely bad idea to try and predict what PK will be assigned at the time of inserting a row.