Corr
Corr

Reputation: 3

How to insert item to the middle of a Django queryset?

I'm trying to sort the queryset in an order that it's sorted by "state" then "city" but I want the city "Other" to always be the last item of each state. I think I can do it by selecting by "state" then append the "Other" at the end then combine all querysets for each state. Is there an easier way to do this? Thanks.

Upvotes: 0

Views: 117

Answers (1)

Ashraful
Ashraful

Reputation: 1974

from django.db.models import Case, When, Value, CharField

SomeModel.objects.annotate(
    custom_city_order=Case(
        When(city="Other", then=Value("ZZZ")),
        output_field=CharField(),
    )
).order_by('state', 'custom_city_order')

This will help you to put a custom value on annotation and then you can order by this annotated value. So, according to your need you can set the value and make order of it.

Upvotes: 1

Related Questions