Let’s say I want to do this in the views
of a Django project:
JavaScript
x
4
1
order_by_query = request.query_params.get("order_by", "")
2
order_by_expression = compile_ob(order_by_query)
3
qs = SomeModel.objects.all().order_by(order_by_expression)
4
I expect the order_by_query to be a string like "field1,-field2"
.
So I will write a function like:
JavaScript
1
2
1
def compile_ob(expression: str) -> ??:
2
My questions are:
- what should I write inside the
compile_ob
function? - what should I return as type?
Advertisement
Answer
You actually don’t need a function to do this. Here is an example:
JavaScript
1
2
1
SomeModel.objects.all().order_by(*order_by_query.split(","))
2
or you can return a list from compile_ob
function and use it with a starred expression.
JavaScript
1
9
1
from typing import List
2
def compile_ob(expression: str) -> List[str]:
3
return expression.split(",")
4
5
# somewhere in views.py
6
order_by_query = request.query_params.get("order_by", 'display_order')
7
order_by_expression = compile_ob(order_by_query)
8
SomeModel.objects.all().order_by(*order_by_expression)
9