Help! Facing error while ordering qs!

Hey,

Below is my implemented code to order my queryset on behalf of the reverse related fields but I am getting error if I’m using distinct, I am bounded to use distinct as I want unique services only which must be ordered by given argument in order by.

filtered_qs = service_filter.qs
ordered_qs = filtered_qs.order_by("-my_services__my_experience__no_of_years_of_experience")
distinct_qs = ordered_qs.distinct("service_id")

but facing the below error:

psycopg2.errors.InvalidColumnReference: SELECT DISTINCT ON expressions must match initial ORDER BY expressions

Your help would be reallly appreciated.

I am trying to implement dynamic sorting or ordering with FilterSet - Ordering Filter.

Thanks in advance!

I think this pretty much explains the issue and what must be done to correct this.

Whatever you use in the distinct clause must be the leading elements of the order_by clause.

See the second Note box in the docs at distinct.

I understood that well but but but, What if I am having a requirement to implement the same, because as per the tagged forum shared by @KenWhitesell I am bounded to use my_services__my_experience__no_of_years_of_experience as distinct but I need the distinct service id instead, I hope you got me there?

I understand what you want. However, the orm requires that you specify whatever fields are in the distinct clause be used as the first fields in the order_by clause. See the examples in the referenced docs.

Basically, what this means is that you may need to handle some of this logic within your code - that the orm may not strictly be able to retrieve the results you want in the order that you want them.