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?
last() to retrieve last and Model. objects. all().
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.
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 .
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With