Django-filter: Custom names in URL for query params of range filter ?

Created on 20 Sep 2015  路  3Comments  路  Source: carltongibson/django-filter

I was wondering if it's possible to rename the field names used in the URL for query params.
Currently

class TransactionFilter(django_filters.FilterSet):
    created = django_filters.DateFromToRangeFilter()
    class Meta:
        model = models.Transaction
        fields = ('created', )

and the request looks like

/api/transaction?created_0=2015-01-01&created_1=2015-01-02

This is working properly but it's not very intuitive. I was wondering if there is any way I can use different names for the range fields, for example

/api/transaction?created_since=2015-01-01&created_until=2015-01-02

Thanks, Haki.

Most helpful comment

Here's an example of subclassing MultiWidget to do this; I used start and end as the field names:

from django.utils.safestring import mark_safe

from django_filters.fields import DateRangeField
from django_filters.filters import RangeFilter
from django_filters.widgets import RangeWidget


class StartEndRangeWidget(RangeWidget):
    """
    A range widget that uses 'start' and 'end' instead of '0' and '1'.
    """

    attr_names = ('start', 'end')

    def render(self, name, value, attrs=None):
        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized

        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)

        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')

        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None

            if id_:
                final_attrs = dict(final_attrs,
                                   id='%s_%s' % (id_, self.attr_names[i]))

            output.append(widget.render(name + '_%s' % self.attr_names[i],
                                        widget_value, final_attrs))

        return mark_safe(self.format_output(output))

    def value_from_datadict(self, data, files, name):
        return [widget.value_from_datadict(data, files,
                                           name + '_%s' % self.attr_names[i])
                for i, widget in enumerate(self.widgets)]


class StartEndDateRangeField(DateRangeField):
    """
    A DateRangeField that uses 'start' and 'end'.
    """

    widget = StartEndRangeWidget


class StartEndDateFromToRangeFilter(RangeFilter):
    """
    A RangeFilter that uses 'start' and 'end'.
    """

    field_class = StartEndDateRangeField

All 3 comments

Hmmm. I think the answer here is _not really_ 鈥斅爑nless you want to get your hands dirty...

The logic for the _0, _1 appendages comes all the way from django.forms.widgets.MultiWidget.render. (RangeFilter uses RangeField which uses RangeWidget which is a MultiWidget subclass.)

You're free to implement render to get the naming you want. You'd need a matching value_from_datadict too.

Here's an example of subclassing MultiWidget to do this; I used start and end as the field names:

from django.utils.safestring import mark_safe

from django_filters.fields import DateRangeField
from django_filters.filters import RangeFilter
from django_filters.widgets import RangeWidget


class StartEndRangeWidget(RangeWidget):
    """
    A range widget that uses 'start' and 'end' instead of '0' and '1'.
    """

    attr_names = ('start', 'end')

    def render(self, name, value, attrs=None):
        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized

        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)

        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')

        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None

            if id_:
                final_attrs = dict(final_attrs,
                                   id='%s_%s' % (id_, self.attr_names[i]))

            output.append(widget.render(name + '_%s' % self.attr_names[i],
                                        widget_value, final_attrs))

        return mark_safe(self.format_output(output))

    def value_from_datadict(self, data, files, name):
        return [widget.value_from_datadict(data, files,
                                           name + '_%s' % self.attr_names[i])
                for i, widget in enumerate(self.widgets)]


class StartEndDateRangeField(DateRangeField):
    """
    A DateRangeField that uses 'start' and 'end'.
    """

    widget = StartEndRangeWidget


class StartEndDateFromToRangeFilter(RangeFilter):
    """
    A RangeFilter that uses 'start' and 'end'.
    """

    field_class = StartEndDateRangeField

Hey @beaugunderson, worth mentioning that in some cases (such as mine) its easier to use two date fields with lt / gt .

Was this page helpful?
0 / 5 - 0 ratings