Skip to content
Advertisement

How to return a string expression for order_by args in django queryset?

Let’s say I want to do this in the views of a Django project:

order_by_query = request.query_params.get("order_by", "")
order_by_expression = compile_ob(order_by_query)
qs = SomeModel.objects.all().order_by(order_by_expression)

I expect the order_by_query to be a string like "field1,-field2".

So I will write a function like:

def compile_ob(expression: str) -> ??:

My questions are:

  1. what should I write inside the compile_ob function?
  2. what should I return as type?

Advertisement

Answer

You actually don’t need a function to do this. Here is an example:

SomeModel.objects.all().order_by(*order_by_query.split(","))

or you can return a list from compile_ob function and use it with a starred expression.

from typing import List
def compile_ob(expression: str) -> List[str]:
    return expression.split(",")

# somewhere in views.py
order_by_query = request.query_params.get("order_by", 'display_order')
order_by_expression = compile_ob(order_by_query)
SomeModel.objects.all().order_by(*order_by_expression)
1 People found this is helpful
Advertisement