Thinh Phan
Thinh Phan

Reputation: 655

How to change the default ordering of a query?

I don't want any ordering to be applied to a query. So, I have a QuerySet follow as:

question_obj = Question.objects.filter(pk__in=[100,50,27,35,10,42,68]).order_by()

However, when I retrieve the results, they are always ordered by questionID. I iterate the question_obj and this is the result:

for obj in question_obj:
   obj.questionID

The result is displayed such as:

10L
27L
35L
42L
50L
68L
100L

Upvotes: 3

Views: 3461

Answers (4)

Alasdair
Alasdair

Reputation: 308939

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

Upvotes: 2

fourk
fourk

Reputation: 2272

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('?')

Upvotes: 2

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53990

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

Upvotes: 0

Peter Rowell
Peter Rowell

Reputation: 17713

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

Django QuerySet API - order_by()

Upvotes: 0

Related Questions