silentsokolov / django-admin-rangefilter

A Django app that lets you filter data by date range and numeric range in the admin UI
MIT License
713 stars 106 forks source link

Using filters with annotated fields #89

Closed last-partizan closed 1 year ago

last-partizan commented 1 year ago

Hi, i want to use NumericRangeFilter on a field that is added by annotate(), by default this isn't working, but i'm bypassing it with following hack:

class CpuCoresFilter(ListFilter):
    # This is a hack to use NumericRangeFilter with custom field.
    # We use ListFilter as a base, to bypass django checks (admin.E113)
    # And we return NumericRangeFilter with custom field and field_path in __new__.
    def __new__(cls, request, params, model, model_admin):
        return NumericRangeFilter(
            PositiveIntegerField(verbose_name=_("CPU cores (total)")),
            request,
            params,
            model,
            model_admin,
            field_path="cpu_cores",
        )

It works, but i don't think this a good idea in the long run.

Any ideas how to do this better?

silentsokolov commented 1 year ago

Looks good I think. Without a native support filter by aggregations you still have to write code.