简体   繁体   English

通过另一个字典订购 Django 查询集

[英]Order a Django queryset by another dict

So, right now I have this model and a calculated dictionary所以,现在我有这个模型和一个计算字典

class User(models.Model):
    user_id = models.AutoField(primary_key=True)


#scores dict {user_id: score}
scores = {1: 9, 2: 2, 3: 1, 4: 5}

I need to order the queryset based on each user score in the scores dict.我需要根据分数字典中的每个用户分数对查询集进行排序。 Something like this像这样的东西

Views.py视图.py

queryset.annotate(score=scores['user_id']).order_by('score')

You can do this, but this is rather "strange":你可以这样做,但这很“奇怪”:

from django.db.models import Case, IntegerField, Value, When

queryset.annotate(
    score=Case(
        *[When(user_id=k, then=Value(v)) for k,v in scores.items()]
        default=None,
        output_field=IntegerField(null=True)
    )
).order_by('score')

It is probably better to just store the scores in the related User model (to which the user_id is referring).最好将分数存储在相关的User模型( user_id所指的)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM