[英]How to build a queryset in a specific order in Django
我正在尝试列出用户的个人资料。 我想以这样一种方式列出它们,即与用户相同的城市的配置文件应该放在第一位,然后下一个优先级应该是 state,然后是国家,最后是配置文件的 rest。 这是我尝试过的。 model
class Profile(models.Model):
uuid = UUIDField(auto=True)
user = models.OneToOneField(User)
country = models.ForeignKey(Country, null=True)
state = models.ForeignKey(State, null=True)
city = models.ForeignKey(City, null=True)
views.py current_user = Profile.objects.filter(user=request.user)
profiles_city = Profile.objects.filter(city=current_user.city)
profiles_state = Profile.objects.filter(state=current_user.state)
profiles_country = Profile.objects.filter(country=current_user.country)
profiles_all = Profile.objects.all()
profiles = (profiles_city | profiles_state | profiles_country | profiles_all).distinct()
但它产生与 Profile.objects.all() 相同的结果
请帮我。 提前致谢
您需要QuerySet
的order_by
方法,该方法根据传递的参数对对象进行排序; 这是在数据库上完成的:
Profile.objects.order_by(
'current_user__city',
'current_user__state',
'current_user__country',
)
编辑:
如果您想按登录用户的city
、 state
和country
/地区名称进行排序,您可以在 Python 级别上执行此操作,使用sorted
和可调用的自定义key
:
from functools import partial
def get_sort_order(profile, logged_in_profile):
# This is a simple example, you need to filter against
# the city-state-country combo to match precisely. For
# example, multiple countries can have the same city/
# state name.
if logged_in_profile.city == profile.city:
return 1
if logged_in_profile.state == profile.state:
return 2
if logged_in_profile.country == profile.country:
return 3
return 4
logged_in_profile = request.user.profile # logged-in user's profile
get_sort_order_partial = partial(get_sort_order, logged_in_profile=logged_in_profile)
sorted(
Profile.objects.all(),
key=get_sort_order_partial,
)
在数据库级别上做同样的事情,使用Case
和When
有一个 Python if
- elif
- else
like 构造:
from django.db.models import Case, When, IntegerField
Profile.objects.order_by(
Case(
When(city=logged_in_profile.city, then=1),
When(state=logged_in_profile.state, then=2),
When(country=logged_in_profile.country, then=3),
default=4,
output_field=IntegerField(),
)
)
这将产生一个查询集,并且还具有更快的附加优势,因为所有操作都将在数据库上完成( SELECT CASE WHEN...
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.