Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get records from a Django database using a list of IDs in a specific order

I am trying to create a Django queryset that returns records in a specific order that matches a list of IDs.

My list of IDs is:

[34,12,4,89,3,67,11]

If I run the following query:

queryset = Item.objects.filter(pk__in=[34,12,4,89,3,67,11])

The query returns records in the ID order:

3,4,11,12,34,67,89

Is there any way to make the query return the records in the same order as the list?

If not is there a way to re-order the query result into the required order?

like image 500
Bill Noble Avatar asked Nov 09 '22 15:11

Bill Noble


1 Answers

Note: Adding this as an answer because OP asked about the approach in the comments of the original question. Showing the snippets in comments didn't allow fenced code blocks.

In the comments on the original question, I mentioned an alternative solution storing your order numbers in a model field, so that ordered queries would be simpler.

One use case for this is if you have a queue of objects where each item is a movie and the user is deciding which order to watch them. You might want to let a Django admin or a user re-order the items (hence making it a field). For the sake of a simple example let's assume there is only one user so we'll build the ordering into the model, as opposed to making a custom table to join through Item and User models.

The model:

class Item(models.Model):
    # ...
    my_order = models.PositiveIntegerField(unique=True)

Set the attribute either at creation or later:

Item.objects.create(id=34, my_order=1)
Item.objects.create(id=12, my_order=2)
Item.objects.create(id=4, my_order=3)
# ...

Of course, you could create them and set my_order in any order you wished, and the result will still be the same.

Retrieve the objects in desired order:

queryset = Item.objects.order_by('my_order')
like image 195
Taylor D. Edmiston Avatar answered Nov 14 '22 21:11

Taylor D. Edmiston