Dot in query parameter name? #1372
-
Hi, I am building REST API and I started using Is it possible to do this in django-filter? I was searching for the answer, but couldn't find it anywhere. Since filter field names correspond to parameter names and dot cannot be a part of a valid Python variable name I am not sure if this is possible. My current implementation looks like this: class ArticleFilter(filters.FilterSet):
age__gt = filters.NumberFilter(field_name="age", lookup_expr="gt")
class Meta:
model = Article
fields = ["age__gt"] |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You'd need to use a custom widget, mapping from the query string argument in |
Beta Was this translation helpful? Give feedback.
-
Thanks for the solution! For anyone having the same issue in the future, here's my implementation class MapQueryParamNameWidget(forms.Widget):
"""Convert query parameter names using mapping dictionary. This can be used if your query
parameter names contains characters that are not allowed in valid Python variables i.e. dots.
Args:
mapping (dict):
Mapping used in string replace method. For example mapping = {".", "__"} would turn
query parameter name "age.gt" into "age__gt".
"""
def __init__(self, mapping):
super().__init__()
if not isinstance(mapping, dict):
raise TypeError("mapping should be a dict")
self.mapping = mapping
def value_from_datadict(self, data, files, name):
mapped_data = dict()
for param, value in data.items():
for k, v in self.mapping.items():
param = param.replace(k, v)
mapped_data[param] = value
# turn dict back into QueryDict
data = QueryDict("", mutable=True)
data.update(mapped_data)
return super().value_from_datadict(data, files, name) with usage: class ArticleFilter(filters.FilterSet):
age__gt = filters.NumberFilter(field_name="age", lookup_expr="gt", widget=MapQueryParamNameWidget({".", "__"}))
class Meta:
model = Article
fields = ["age__gt"] |
Beta Was this translation helpful? Give feedback.
You'd need to use a custom widget, mapping from the query string argument in
value_from_datadict