Toggle sorting ascending descending per column.

This must/should be a common issue but I’m not seeing it at the moment.

I’m using a listview with pagination.
In order to sort per column I’m passing ?page=1&sort_col=1 as parameter.
In the view class
when overriding get_queryset I’m doing :
sort_col = self.request.GET.get('sort_col')
And then adapt the queryset.

I’d like to toggle between ascending and descending but this tag:

<a href="?sort_col=0&sort_dir={% if sort_col == 0 %}{% if sort_dir == 'asc' %}desc{% else %}asc{% endif %}{% else %}asc{% endif %}&page={{page_obj.number}}">

Isn’t doing it for me.

As I’m surely not the first to ask, what’s the most direct approach here?

Can you be more specific about “Isn’t doing it for me.”? What, exactly, is not what you expect?

If you view that <a href...> tag by doing View Source in your browser, what does it look like?

Are you passing sort_col and sort_dir to your template in the context?

If so, is the value you’re passing for sort_col actually an integer (0), or a string ("0")?

You’re right I was a bit scarce on info.

the value is indeed passed as an int and works fine.

The idea is to switch asc and desc.

the url always looks like this :

/?sort_col=0&sort_dir=asc&page=1

Ofcourse the sort_col or page=1 changes.
If I manully change the sort_dir to desc it does sort in descending order.
Clicking it will change it to asc but from asc to desc, not so much.

The template wants to check the sort_dir but I’m assuming the template cannote access the sort_dir in the url directly.
I’m also assuming that my view function gets recalled every update so it has no persistent state.

There must be a way to solve this :wink:

What does your view look like that is supposed to render this? Are you sure that you’re passing sort_dir into the template through the context?

Thanks for contributing.
You had me thinking by your question.

I wasn’t passing these vars in the context.
Works now!

Thank you