year filter applied to multiple attributes/classes/models


I have a Model with multiple linked other models. Each of that linked models has the attribute year (e.g. Status - year of the status, investment - year of the investment, etc. ) for each of them I have a new filter to filter for the year the status was active or the investment took place. Now I wondered if it is possible to filter with just ONE filter field through all the linked models/attributes. So when I put 2020 in the filter I’d get all investments made in this year PLUS all the status.

class CalculationPlantFilter(django_filters.FilterSet):
    status_of_plant = django_filters.ChoiceFilter(choices=StatusOfPlants.StatusChoices.choices)
    status_of_plant__year = django_filters.NumberFilter(field_name='status_of_plant', lookup_expr='year')
    operatinghour__year = django_filters.NumberFilter(field_name='operatinghour', lookup_expr='year')
    number_of_employees__year = django_filters.NumberFilter(field_name='number_of_employees', lookup_expr='year')
    investment_in_plant__year = django_filters.NumberFilter(field_name='investment_in_plant', lookup_expr='year')
    design_capacity__year = django_filters.NumberFilter(field_name='design_capacity', lookup_expr='year')

    class Meta:
        model = Plant
        fields = '__all__'

It would be nicer to just have to set the year once instead of multiple times.
Does anyone have an idea if this is possible and where I could find the information I need (or has a solution).

Any help is appreaciated and welcome! :slight_smile:

Best regards,

This is a django-filter plug in question, you may find insight how to do this here

Do you know where I can find it in the documentation? It seems that I keep overreading it or just don’t see that it is the solution or can’t transfer it to my case.
I read this page multiple times now but keep missing it.

I don’t know your model layout, but maybe something like this:

from django.db.models import Q

class CalculationPlantFilter(django_filters.FilterSet):

    class Meta:
        model = Plant
        fields = '__all__'

    def year_filter(self, queryset, name, value):
        return queryset.filter(
            Q(foo__year=value) | Q(bar__year=value)

You can see an example of constructing ones own filter here: Keyword-only Arguments example

1 Like