如何在Django的查询集中获取倒数第二条记录? [英] How to get second last record in a queryset in Django?
本文介绍了如何在Django的查询集中获取倒数第二条记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 employees_salary
的模型,我需要获得员工的第二高薪水.
I have a model named employees_salary
and I need to get second highest salary of employee.
我知道我可以过滤 latest()
, first()
, last()
**,这些都可以,但是如何过滤倒数第二?我想念什么吗?
I know that I can filter latest()
, first()
, last()
** and these are working, but how to filter second last? Am I missing something?
推荐答案
使用带有反向过滤器(-)的order_by,然后使用[1]抓取第二个对象.
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
这篇关于如何在Django的查询集中获取倒数第二条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文