Reputation: 202
I have to do custom order by in my code,
Consider below E.g:
class Car(models.Model):
type
brand
Whenever I do order by using brand I get below query set
cars = ["Benz","BMW","Ford","Honda","Suzuki"]
I need to do order by brand in which "BMW" should always come at last like below queryset,
cars = ["Benz","Ford","Honda","Suzuki", "BMW"]
Note: I don't want to use/ convert it as list. I need to do some queryset operations (like values_list) on this after order by.
Upvotes: 1
Views: 4964
Reputation: 202
You can try to do it like here:
https://stackoverflow.com/a/2176471/4971083
It's the solution for ordering your records by specific value in Django.
car = Car.objects.filter(product__id=product_id).extra(
select={'is_top': " brand='BMW'"})
car = car.extra(order_by = ['is_top'])
Upvotes: 3