Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 643
Kamlesh Avatar asked Feb 10 '16 05:02

Kamlesh


People also ask

How do I get the last element in QuerySet?

last() to retrieve last and Model. objects. all().

How do you write a second highest salary query?

Now, to find the second highest salary, we nest the above query into another query as written below. SELECT MAX(SALARY) FROM Employee WHERE SALARY < (SELECT MAX(SALARY) FROM Employee); This query will give you the desired output i.e 12000, which is the second highest salary.

How does QuerySet work in Django?

A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT .

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data. In this tutorial we will be querying data from the Members table.


2 Answers

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
like image 79
Aviah Laor Avatar answered Sep 18 '22 21:09

Aviah Laor


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
like image 25
Vikram Singh Chandel Avatar answered Sep 21 '22 21:09

Vikram Singh Chandel