Monday, 11 November 2019

django-tables2/django-filter - pagination with filterclass

Good Afternoon,

I am using a custom django-filter in django-tables2 to search all fields with a single input. Ive just noticed that when I search I lose my pagination menu.

this is the link to the filter code https://spapas.github.io/2016/09/12/django-split-query/

here's my filter

class SiteFilterEx(django_filters.FilterSet):
    ex = django_filters.CharFilter(label='Ex filter', method='filter_ex')
    search_fields = ['location', 'bgp_as', 'opening_date','town','postcode']

    def filter_ex(self, qs, name, value):
        if value:
            q_parts = value.split()

            # Use a global q_totals
            q_totals = Q()

            # This part will get us all possible segmantiation of the query parts and put it in the possibilities list
            combinatorics = itertools.product([True, False], repeat=len(q_parts) - 1)
            possibilities = []
            for combination in combinatorics:
                i = 0
                one_such_combination = [q_parts[i]]
                for slab in combination:
                    i += 1
                    if not slab: # there is a join
                        one_such_combination[-1] += ' ' + q_parts[i]
                    else:
                        one_such_combination += [q_parts[i]]
                possibilities.append(one_such_combination)

            # Now, for all possiblities we'll append all the Q objects using OR
            for p in possibilities:
                list1=self.search_fields
                list2=p
                perms = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]

                for perm in perms:
                    q_part = Q()
                    for p in perm:
                        q_part = q_part & Q(**{p[0]+'__icontains': p[1]})
                    q_totals = q_totals | q_part

            qs = qs.filter(q_totals)
        return qs    

    class Meta:
        model = Site
        fields = ['ex']     
        form = SiteFilterForm  

in my template I can use:

Showing  of  records 

but the default Django-tables uses

Showing  to  of  records 

and when I filter the pagination is gone completely.

I think I need to return a paginate with the same name some how? but am unsure of what I need to do?



from django-tables2/django-filter - pagination with filterclass

No comments:

Post a Comment