1

My initial question was here and was related to the postgres backend. Postgres subquery, ordering by subquery

Now my problem has moved onwards to the Django ORM layer. I essentially want to order a query by a postgres function ('idx', taken from the above stackoverflow work)

I've gone through trying to use model.objects.extra(order_by ) or simply order_by but I believe both of these need the order_by parameter to be an attribute or a field known to Django.

I'm trying to think how to solve this without having to revert to using an entirely raw SQL query through a model manager.

1 Answer 1

6

You can use extra to add the function result to your query and then order by it. Something like:

MyModel.objects.extra(select={'idx': 'idx(foo, bar)'}, order_by=['idx'])
Sign up to request clarification or add additional context in comments.

1 Comment

that's a brilliant answer. I wish I could give you more than a plus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.