thebiglife
thebiglife

Reputation: 1889

django - order query set by postgres function

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.

Upvotes: 1

Views: 703

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

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'])

Upvotes: 6

Related Questions