Kamlesh
Kamlesh

Reputation: 2056

How to get second last record in a queryset in Django?

I have a model named employees_salary and I need to get second highest salary of employee.

I know that I can filter latest(), first(), last()** and these are working, but how to filter second last? Am I missing something?

Upvotes: 11

Views: 19503

Answers (3)

Abdullah Atif
Abdullah Atif

Reputation: 35

This will also work, if you try it like this:

models.py:

class Post(models.Model):   
    title = models.CharField()
    body = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)

views.py:

def postlist(request):
    latest_post = Post.objects.order_by('-pub_date')[0]
    secondlast_post =  Post.objects.order_by('-pub_date')[1]
    context = {
         'latest_post' : latest_post, 'secondlast_post' : secondlast_post ,
    }
    return render(request, 'yourtemplate.html', context)

Upvotes: 0

Aviah Laor
Aviah Laor

Reputation: 3658

Use order_by with a reverse filter (-) and then grab the second object by using [1].

class Salaries(models.Model):

  employee_name = models.CharField(max_length=255)
  salary = models.IntegerField()


q = Salaries.objects.all().order_by('-salary')

second_highest_paid_name = q[1].employee_name

Upvotes: 23

Vikram Singh Chandel
Vikram Singh Chandel

Reputation: 1308

This way will also work

class EmployeeSalary(models.Model):    
    employee_name = models.CharField(max_length=255)
    salary = models.IntegerField()

#code for view
q = EmployeeSalary.objects.all().order_by('-salary')[1:1]
second_paid_name = q[0].employee_name
second_paid_salary = q[0].salary

Upvotes: 5

Related Questions