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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With