Tsuna
Tsuna

Reputation: 2196

how do I sort the queryset by a property's property? django

I have a function which returns a queryset but now I would like to sort the queryset but I am not sure how this can be done.

def get_queryset(self):
    print('--------------------------------')
    # print(self.request.basket.all_lines()[0].product.upc)
    print('--------------------------------')
    return self.request.basket.all_lines()

self.request.basket.all_lines() would return me a queryset but I would like to sort it by it's product's upc

I am able to get the upc by print(self.request.basket.all_lines()[0].product.upc)

I made sure that .product.upc does exist and I am in the right direction.

Can someone please give me a hand?

Upvotes: 1

Views: 1745

Answers (2)

Domen Blenkuš
Domen Blenkuš

Reputation: 2242

Have you tried this?

return self.request.basket.all_lines().order_by('product__upc')

Upvotes: 2

Patrick Gallagher
Patrick Gallagher

Reputation: 193

How about using python's sorted method?

sorted(self.request.basket.all_lines(), key=lambda x: x.product.upc)

Upvotes: 0

Related Questions