Skip to content
Advertisement

Django 4.x – Conditional order_by of a QuerySet

The Objective

The objective is to conditionally order a QuerySet by one of three different date fields in the view based on another field in the model. Since conditional ordering cannot be accomplished with Class Meta I am exploring accomplishing this objective in the view.

Here is the relevant excerpt from models.py:

JavaScript

The relevant fields in the model are:

  • reading_progress
  • date_added
  • date_started
  • date_completed

Each date field corresponds to a status value. I want to be able to order_by the QuerySet in the view by the field reading_progress:

  • When reading_progress == ‘1) On Reading List’ then order by date_added
  • When reading_progress == ‘2) Reading In Progress’ then order by date_started
  • When reading_progress == ‘3) Completed Reading’ then order by date_completed

Research This Far

I did some research and found a useful looking QuerySet API called, annotate(). This looks to be way to go (Django docs).

However, my implementation is not working. Here’s what I currently have in views.py:

JavaScript

The Django docs appeared to suggest that:

  • I could filter
  • and then annotate on the filtered QuerySet
  • With additional research I concluded that I could use F() as a way of implementing the query within the annotate() API

However, my implementation is not quite working. This is the Traceback reporting a NameError:

JavaScript

I feel like I am close but am currently scratching my head. The example snippets I have seen make use of Case but for some reason I’m getting an error saying I’ve not defined Case. This leads me to believe that maybe I’m approaching this the wrong way.

Advertisement

Answer

You have to import the relevant parts within views.py

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement