Django QuerySet Custom Ordering by ID

后端 未结 2 490
攒了一身酷
攒了一身酷 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 04:07

    I do not know of a way to do this using a filter condition. If your database will return the rows in the order of the IN clause then you may be able to combine Django's extra method with the ROWNUM provided by your database to achieve this.

    For e.g.:

    queryset = MyModel.objects.filter(pk__in=[pk_list]).extra(
           select: {'rownum': 'row_num()'}).order_by('rownum')
    

    Where row_num() is assumed to be a database function that returns the row number of the current row. Postgresql 8.4+ supports row_num() but I do not know how to order the rows returned using the same order as the values in the IN clause.

    I think a better way would be to sub class ModelMultipleChoiceField and add custom sorting logic when rendering.

提交回复
热议问题