diff --git a/datasette/facets.py b/datasette/facets.py index 8c09e1dc13..55505c38e4 100644 --- a/datasette/facets.py +++ b/datasette/facets.py @@ -264,6 +264,10 @@ async def facet_results(self): column_qs = column if column.startswith("_"): column_qs = f"{column}__exact" + # ?column=x and ?column__exact=x are equivalent filters, + # so check for both, https://github.com/simonw/datasette/issues/2011 + if (f"{column}__exact", str(row["value"])) in qs_pairs: + column_qs = f"{column}__exact" selected = (column_qs, str(row["value"])) in qs_pairs if selected: toggle_path = path_with_removed_args( diff --git a/tests/test_facets.py b/tests/test_facets.py index b8eb6e61b6..91e33be145 100644 --- a/tests/test_facets.py +++ b/tests/test_facets.py @@ -151,6 +151,54 @@ async def test_column_facet_results(ds_client): ] == buckets +@pytest.mark.asyncio +async def test_column_facet_results_selected_by_exact_filter(ds_client): + # The filter form produces ?column__exact=x rather than ?column=x - + # both should mark the matching facet value as selected + # https://github.com/simonw/datasette/issues/2011 + facet = ColumnFacet( + ds_client.ds, + Request.fake("/?_facet=state&state__exact=MI"), + database="fixtures", + sql="select * from facetable", + table="facetable", + ) + buckets, timed_out = await facet.facet_results() + assert [] == timed_out + assert buckets == [ + { + "name": "state", + "type": "column", + "hideable": True, + "toggle_url": "/?state__exact=MI", + "results": [ + { + "value": "CA", + "label": "CA", + "count": 10, + "toggle_url": "http://localhost/?_facet=state&state__exact=MI&state=CA", + "selected": False, + }, + { + "value": "MI", + "label": "MI", + "count": 4, + "toggle_url": "http://localhost/?_facet=state", + "selected": True, + }, + { + "value": "MC", + "label": "MC", + "count": 1, + "toggle_url": "http://localhost/?_facet=state&state__exact=MI&state=MC", + "selected": False, + }, + ], + "truncated": False, + } + ] + + @pytest.mark.asyncio async def test_column_facet_results_column_starts_with_underscore(ds_client): facet = ColumnFacet(