cjahangir
cjahangir

Reputation: 1797

Ordering filtered queryset according to a order of list

I have a list described below. I want a queryset which will be ordered according to the order of list

list

 id_list = [3,1,2]

queryset

   queryset = Variant.objects.filter(pk__in=id_list)

the queryset gives objects in the order below:

obj1
obj2
obj3

but i want the objects according to order in the given list:

obj3
obj1
obj2

how??

Upvotes: 4

Views: 1648

Answers (2)

Yevgeniy Shchemelev
Yevgeniy Shchemelev

Reputation: 3651

Don't define ordering in code - add ordering column to your table and order by it. That's it.

class Variant(models.Model):
    order = models.IntegerField()
    ...

Variant(ordering=3).save() # id == 1
Variant(ordering=1).save() # id == 2
Variant(ordering=2).save() # id == 3

queryset = Variant.objects.filter(pk__in=id_list).order_by('order')

So you will have queryset according to desirable order.

Otherwise google: django convert list to queryset and use Sayse answer as base for your code. One example: django - convert a list back to a queryset

Upvotes: 1

Sayse
Sayse

Reputation: 43300

I don't think you could do this with a queryset (nor do I understand why you want to...)

You could do it with a map, but be warned, this will resolve the query and be potentially inefficient.

variants = list(map(lambda id: Variant.objects.get(pk=id), id_list))

Upvotes: 0

Related Questions