I have a list of IDs for objects that I need to grab, then I have to sort them by their timestamp. Here's how I was going to do it:
For i in object_ids:
instance = Model.objects.get(id = i)
# Append instance to list of instances
#sort the instances list
But there are two things that bother me:
Thanks,
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.
The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .
all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.
This can be done using such a code:
objects = Model.objects.filter(id__in=object_ids).order_by('-timestamp')
the order_by
can be positive or negative timestamp
, depending how you want it sorted.
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