Django QuerySet Custom Ordering by ID

后端 未结 2 483
攒了一身酷
攒了一身酷 2020-12-14 03:18

Given a list of ids/pks, I\'d like to generate a QuerySet of objects ordered by the index in the list.

Normally I\'d begin with:

pk_list         


        
2条回答
  •  轮回少年
    2020-12-14 03:46

    There isn't a built-in way to do this.

    If you're using MySQL, you can use that database's FIELD() function to set up a custom ordering sequence on your model, and sort by that. This would work:

    pk_list = [5, 9, 2, 14]
    ordering = 'FIELD(`id`, %s)' % ','.join(str(id) for id in pk_list)
    queryset = MyModel.objects.filter(pk__in=[pk_list]).extra(
                   select={'ordering': ordering}, order_by=('ordering',))
    

提交回复
热议问题