Reputation: 718
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
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