How to order queryset by values in the list so that they can be at the top?

I needed to customize list method of ModelViewSet to reorder the items.
Basically, I have a list of items that should be on the top of the list.
I have ids of those top items and wondering how I can order the queryset with that ids list.
I do mind a lot about performance issues.
However I’d like to consider any possible solutions.

Thanks.

Is there some attribute of those items which can be used to sort those items?

Do those items need to be sorted by any particular order within that group?

Do the rest of the items in the list need to be sorted by some sequence?

What is it about that first group that distinguishes them from the rest of the items?

If you’ve got a way of breaking the full list into two separate queries, you can use the union() function to join those two querysets into one list.

Hi, Ken!
Thanks for your attention.

  1. Is there some attribute of those items which can be used to sort those items?
    No, I don’t think there are such attributes.

  2. Do those items need to be sorted by any particular order within that group?
    I just want to put those items, whose ids are in the selected list, at the top. No particular order.

  3. Do the rest of the items in the list need to be sorted by some sequence?
    No need to sort the items in the list.

  4. What is it about that first group that distinguishes them from the rest of the items?
    They are selected items like favorite items or high priority items, which should be at the top of the list on front-end side.

My question.
Can I use that union() function to join two querysets, not the data?

Thanks

Basically, I did it using django.db.models.When and Case.
But since I do mind a lot in terms of performance, I am still wondering if I could find a better way than this.

I’d love to listen to your opinions.

FYI, the list of selected items won’t that big, maybe up to 10 ~ 20.

Hi, Ken!

I am also curious to know whether union() between two querysets does reorder the items or not.

I think they will break the order of two querysets and order the whole stuff again.

There are some implications of sequencing of the two querysets in a union depending upon what order_by clauses may or may not be included. So yes, that’s probably not a solution.

Without knowing more of the specifics of the data involved, it’s going to be tough to offer a definitive solution.

But from the information you have provided, there are two thoughts that come immediately to mind:

  1. Worrying about performance of a query selecting 10 - 20 items appears to me to be misplaced effort. Unless you’ve got some benchmarks showing that there is an actual performance problem, your time is likely better spent elsewhere.

  2. I’d go with converting both querysets to lists in the view and concatenating the two lists. That’ll maintain order and will be effectively transparent to the template.