Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get a QuerySet from array of id's in specific order

Tags:

arrays

django

heres a quick one for you:

I have a list of id's which I want to use to return a QuerySet(or array if need be), but I want to maintain that order.

Thanks

like image 546
neolaser Avatar asked Feb 06 '11 23:02

neolaser


People also ask

Does order of filter matter Django?

If you are just doing two simple filter operations, then you're correct that order doesn't matter, but be careful. There are examples of when the order of your queryset methods do matter: https://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses.

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.

What is ID __ in in Django?

In Django, we can use the id__in query with a queryset to filter down a queryset based on a list of IDs. However, by default this will fail if your IDs are UUIDs.


2 Answers

Since Django 1.8, you can do:

from django.db.models import Case, When  pk_list = [10, 2, 1] preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)]) queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved) 
like image 81
Soitje Avatar answered Sep 24 '22 06:09

Soitje


I don't think you can enforce that particular order on the database level, so you need to do it in python instead.

id_list = [1, 5, 7] objects = Foo.objects.filter(id__in=id_list)  objects = dict([(obj.id, obj) for obj in objects]) sorted_objects = [objects[id] for id in id_list] 

This builds up a dictionary of the objects with their id as key, so they can be retrieved easily when building up the sorted list.

like image 29
Reiner Gerecke Avatar answered Sep 25 '22 06:09

Reiner Gerecke