carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections
https://django-filter.readthedocs.io/en/main/
Other
4.44k stars 767 forks source link

Don't overwrite existing get parameters via DRF Browsable API #1655

Closed stefanofusai closed 5 months ago

stefanofusai commented 5 months ago

First of all, thank you for the awesome library! Great work

A small issue I've encountered is that when I'm using the DRF Browsable API's Filters, if I click on "Submit" existing query params that are not generated by django-filter (that is: search and ordering params, which I handle via DRF's SearchFilter and OrderingFilter) are removed from the resulting URL.

This behavior is even worse when some views require either of those 2 params, such as the search param from SearchFilter. I was able to find this discussion but couldn't understand what the solution would be; furthermore, the linked SO thread is now dead.

So, the question is: how do I avoid existing non django-filter params from being overwritten? And, while I'm at it, I have another question: any idea how I can still show the Filters button on the DRF Browsable API, even on 400 responses?

Thank you very much for the help.

carltongibson commented 5 months ago

Hi @stefanofusai.

The essence of it is that you need to make sure the filter form's values are included in the query string for the request you're making.

There was a good thread on the Django Forum about how to do this with HTMX: https://forum.djangoproject.com/t/using-htmx-and-django-mostly-great-but-how-to-send-along-get-params-with-htmx/24717

TBH I'm not at all sure in these latter days how you'd do that with the DRF Browsable API. (I can't recall the customisation options. It's been a number of years since I've needed to do that.)

stefanofusai commented 5 months ago

Appreciate the quick reply, I guess I'll just forward this to the DRF team.

On a side note, would you be able to point me to the best practice/libraries to implement facet counts in my DRF API? What I would like to do is to, for each filter, have a dictionary of the number of counts for each filter result (or min/max ranges, for price or date filters)

P.S. huge fan of your podcast! Keep it up

carltongibson commented 5 months ago

Thanks, glad you like it! 🎙️

Facet counts... — I'd glance at the Django 4.x code for the admin, but the essence is you need to get the filtered query set and then do a count call for each one, and add that to your response. (How you do that exactly in your case you'll have to think about.)