首先订购带有特定对象的Django查询集 [英] Order a django queryset with specific objects first
问题描述
我有一个显示在如下模板中的用户列表.
I have a list of users displaying in templates like the following.
{% for u in users_list %}
{{u.name}}
{% endif %}
是否可以将两个或多个用户排在顶部?
Is there a way to rank two or more users at the top If I want to?
例如,有一个用户,当当前用户访问该列表时,我可以在将变量发送到模板之前排除我,从而将他排名在前,而没有特定的顺序.
For instance with one user, when the current user visits that list, I can rank him in the top without a specific ordering by excluding me before sending the variable to template.
1) me
2) user2
3) user3
推荐答案
If you want to order specific objects by id at the top of a queryset, you can order on a conditional expression - for example, to put the current user at the top, and order other users by name:
from django.db.models import Case, When
from django.contrib.auth.models import User
users = User.objects.order_by(
Case(When(id=request.user.id, then=0), default=1),
'last_name',
'first_name'
)
要在顶部放置多个对象,只需调整 When
条件:
To put multiple objects at the top, just adjust the When
condition:
ids_at_top = [1, 2]
users = User.objects.order_by(
Case(When(id__in=ids_at_top, then=0), default=1))
我还会考虑是否可以通过更简单的方式实现所需的功能-例如,您可以获取当前用户,将其从主查询集中排除,然后像这样单独显示在模板中
I would also consider though whether you can achieve what you want via simpler means - for example you could get the current user, exclude them from the main queryset, and then display separately in the template, like this
# in the view
current_user = request.user
users = User.objects.exclude(id=current_user.id)
# in the template
{{ current_user.name }}
{% for u in users %}
{{ u.name }}
{% endif %}
这篇关于首先订购带有特定对象的Django查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!