0

I have a query as given below,

new_list = [5, 15, 14, 23, 20]
queryset = Page.objects.filter(id__in=new_list)

When I try this django provides a query set filtered by id in return.

for i in queryset:
    print i.id

The result is [5,14,15,20,23]

But i do not need any ordering.

If I use in_bulk() here I will get a result of type dict in return and with sorted() returns a list. I need a django query set instead of this. Can some one tell me how I can achieve this? My expected results are given below.

type(queryset) >> django.db.models.query.QuerySet
for i in queryset:
    print i.id
>>>[5, 15, 14, 23, 20]

Please help me to find a solution.

Arundas R
  • 770
  • 7
  • 20
  • 2
    But that isn't "no ordering". That's "ordering by the list of IDs I passed in", which is a completely different question. – Daniel Roseman Apr 20 '15 at 11:53
  • Depending on the DBMS you are using, you may implement one of the answers to [this question](http://stackoverflow.com/questions/866465/sql-order-by-the-in-value-list) using the [extra](https://docs.djangoproject.com/en/1.8/ref/models/querysets/#extra) method for example. It might be easier to sort the result using python though. – aumo Apr 20 '15 at 12:05
  • possible duplicate of [Django get a QuerySet from array of id's in specific order](http://stackoverflow.com/questions/4916851/django-get-a-queryset-from-array-of-ids-in-specific-order) – Aylen Apr 20 '15 at 12:09
  • No. I have already explained in the question that my aim is not to get a list. Instead I need a query set as return – Arundas R Apr 20 '15 at 12:34
  • Thanks for hinting me about extra query. :) – Arundas R Apr 20 '15 at 12:41

1 Answers1

0

I have got the answer for my question.

id_list = [10, 3, 13, 4]
clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(id_list)])
ordering = 'CASE %s END' % clauses
queryset = Page.objects.filter(id__in=id_list).extra(
        select={'ordering': ordering}, order_by=('ordering',))

In case I use extra query and hence I will get a queryset object as return, which is what I want.

Arundas R
  • 770
  • 7
  • 20