Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Grab a set of objects from ID list (and sort by timestamp)

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:

  • Is there no way to grab a collection of entries by a list of their IDs - without having to loop?
  • Can I append arbitrary objects to the QuerySet just based on their IDs ?

Thanks,

like image 423
Goro Avatar asked Mar 23 '12 20:03

Goro


People also ask

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.

How do you get or view all the items in a model in Django?

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

What does objects all () return in Django?

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.


1 Answers

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.

like image 100
kender Avatar answered Sep 26 '22 23:09

kender