11. 如何使用Django ORM找到第二大记录?¶
You would across situations when you want to find second highest user depending on their age or salary.
Though the ORM gives the flexibility of finding first()
, last()
item from the queryset but not nth item. You can do it using the slice operator.
我们可以使用切片运算符从查询中找到第N条记录。
>>> user = User.objects.order_by('-last_login')[1] // Second Highest record w.r.t 'last_login'
>>> user.first_name
'Raghu'
>>> user = User.objects.order_by('-last_login')[2] // Third Highest record w.r.t 'last_login'
>>> user.first_name
'Sohan'
User.objects.order_by('-last_login')[2]
only pulls up the required object from db using LIMIT ... OFFSET
. 如果你看一下生成的sql,你会看到类似的东西。
SELECT "auth_user"."id",
"auth_user"."password",
"auth_user"."last_login",
"auth_user"."is_superuser",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."date_joined"
FROM "auth_user"
ORDER BY "auth_user"."last_login" DESC
LIMIT 1
OFFSET 2