[Django]-How to change the default ordering of a query?

2👍

If you want to display the objects in the same order as the list of primary keys, then you could use in_bulk to create a dictionary keyed by pk. You can then use a list comprehension to generate the list of questions.

>>> pks = [100,50,27,35,10,42,68]
>>> questions_dict = Question.objects.in_bulk(pks)
>>> questions = [questions_dict[pk] for pk in pks]
>>> for question in questions:
        print question.pk
100
50
27
35
...

2👍

If you want an unordered collection, use Python’s Set object, documented here: http://docs.python.org/tutorial/datastructures.html#sets

If you want the ordering to be the same as the list you’re passing as the value for pk__in, you could try:

ids = [100,50,27,35,10,42,68]
questions = list(Question.objects.filter(pk__in=ids))
question_obj = sorted(questions, key=lambda x: ids.index(x.id))

EDIT: And because it’s extremely unclear as to what you mean by ‘unordered’ in reference to a data structure that is by definition ordered: Random ordering can be accomplished through the following:

.order_by('?')
👤fourk

0👍

Luke, use the Source, er, the Docs! Yeah, that’s it!

Django QuerySet API – order_by()

0👍

You could do some raw SQL (with FIELD()) a lá:

Ordering by the order of values in a SQL IN() clause

which should allow you to retrieve them in the order suggested in the list.

To run custom SQL with the ORM:

https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly

Leave a comment