Goro
Goro

Reputation: 10249

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:

Thanks,

Upvotes: 21

Views: 18216

Answers (2)

kender
kender

Reputation: 87161

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.

Upvotes: 34

Simeon Visser
Simeon Visser

Reputation: 122376

Try the following:

result = Model.objects.filter(id__in=object_ids)

This returns all Model objects that have their id in the given list of object_ids. This way, you also don't need to append additional models to the resulting QuerySet.

Upvotes: 10

Related Questions