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('?')
- [Django]-NoReverseMatch Reverse for '' with arguments '()' and keyword arguments '' not found
- [Django]-ImportError: cannot import name connections
- [Django]-Django CMS plugin context vs. page context
0👍
Luke, use the Source, er, the Docs! Yeah, that’s it!
- [Django]-Pythonic web-based framework other than Django
- [Django]-Django: How to dynamic filter foreignkey choices by Customizing the Django_Admin
- [Django]-In Django, what does latest('date') return when there's more than one possible result?
- [Django]-Why do you need to use Django REST API?
- [Django]-Serialize a list of objects in json in Django
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
- [Django]-Missing header files while installing packages using pip
- [Django]-TypeError: unhashable type: 'dict' Django
- [Django]-How to implement a queue with django models /database?