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
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.
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.
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.
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)
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.
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