robtus88
robtus88

Reputation: 490

Django filter multiple fields with same choices

I have a model that looks like this:

field_1 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True)
field_2 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True)

I would like to create a filter with django_filters, to combine these 2 separate fields into 1 single ChoiceFilter. How can I do that?

Upvotes: 1

Views: 1370

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can specify method which will be used to filter on custom field:

class YouFilter(FilterSet):
    new_field = ChoiceFilter(method='filter_new_field', choices=FIELD_CHOICES)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'new_field')

    def filter_new_field(self, queryset, name, value):
        return queryset.filter(
            field_1=value,
            field_1=value
        )

Upvotes: 2

Related Questions