简体   繁体   中英

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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