jeevu94
jeevu94

Reputation: 718

Django query to keep perticular item at first and then apply order_by to rest of the items

Let say we have an Article model.

class Article(models.Model):
    id = int
    name = char

i want to get all the articles but the article with name = "stackoverflow" should be the first item in queryset and apply order_by to rest of the items. eg .order_by("name").

what i've achieved so far is

queryset = Article.objects.all().order_by("name")
stackoverflow = queryset.get(name="stackoverflow")
query = queryset.exclude(name="stackoverflow")
articles = []
articles.extend(stackoverflow)
articles.extend(query)

But this hits the database atleast 4 times. Can we do this in a better way?

Upvotes: 1

Views: 711

Answers (1)

Liza Amatya
Liza Amatya

Reputation: 141

from django.db.models import Case, When

articles = Article.objects.order_by(
    Case(When(name="stackoverflow", then=0), default=1)
)

Ref: https://docs.djangoproject.com/en/3.1/ref/models/conditional-expressions/

Order a django queryset with specific objects first

Upvotes: 5

Related Questions