2

So, basically I have a FilterSet I am using with django-tables2. Now I need to use have a single char field which should search two separate fields from the Model.

For example:

ip_addr = django_filters.CharFilter(lookup_expr='icontains')
virtual_ip = django_filters.CharFilter(lookup_expr='icontains')

Above is my current FilterSet. Both these are rendered into two separate fields in the Template. But I want to combine them into a single field in the front end, which looks up either in ip_addr OR in virtual_ip.

Can any one point me in right direction.

Amar C
  • 374
  • 5
  • 17

1 Answers1

3

You can create complex lookups with Q objects inside a custom method for filtering more than one field, like this:

from django.db.models import Q
# ..your other imports..

YouFilterSet(django_filters.FilterSet):
    # ip_addr = django_filters.CharFilter(lookup_expr='icontains')
    # virtual_ip = django_filters.CharFilter(lookup_expr='icontains')
    my_lookup_field = django_filters.CharFilter(label='ip', method='my_lookup_method')

    class Meta:
        # ..your meta attributes..

    def my_lookup_method(self, queryset, name, value):
        return queryset.filter(Q(ip_addr__icontains=value)|Q(virtual_ip__icontains=value))

This will return a Queryset with your value in either your ip_addr or virtual_ip fields. For more info you can check the docs here for Q objects and also here and here for custom methods in Filters.

Jordan Mora
  • 889
  • 6
  • 16