1

Let's say that I have a list of movie ids in a QuerySet in the following format:

movie_ids = [12,4,9,16]

Now, I want to pull the list of corresponding movies. I also want to minimize the number of queries. So I do the following:

movies = Movie.objects.filter(pk__in=movie_ids)

However, this query won't guarantee that movies will have the corresponding movie objects in the same order as they were in movie_ids, will it? Is there anyway to guarantee the order (so that each movie_id corresponds to the correct movie) so I can do something pair the two lists into a dictionary with:

id_movies = dict(zip(movie_ids, movies))

This would then be used in my template in Django.

ArKitect
  • 87
  • 3
  • 7

1 Answers1

2

You can use the dict like

# Create the dict for the movies object.
id_movies = dict([(m.id, m) for m in movies])

# Get the data in order.
order_movies = [id_movies[i] for i in movie_ids]

This way you will get the object in same order which you gave.

Nilesh
  • 20,521
  • 16
  • 92
  • 148
  • 1
    Now we're first creating the list and from that the dict. Is there any reason to not go with `{m.id : m for m in movies}` which does the same (?) thing inline? – Voo Feb 15 '12 at 06:21