Dynamic filter listview django

Django -- Posted on July 31, 2024

Dynamic filter list view djnago

              
                from django.db.models import Q

class BaseListView(ListView):
    def get_queryset(self):
        q_objects = Q()
        queryset = super().get_queryset()
        q = self.request.GET.get('q')
        if q and q != '':
            if not q.startswith('0'):
                try:
                    id = int(q)
                except ValueError:
                    id = None
                if id:
                    queryset = queryset.filter(id=id)
                else:
                    for f in self.model._meta.get_fields():
                        # Check if the field is a ForeignKey or ManyToManyField
                        if f.is_relation and (f.many_to_one or f.one_to_one or f.many_to_many):
                            related_model = f.related_model
                            for related_field in related_model._meta.get_fields():
                                if related_field.__class__.__name__ in ['CharField', 'TextField']:
                                    field_name = f"{f.name}__{related_field.name}"
                                    q_objects |= Q(**{f"{field_name}__icontains": q})
                        elif f.__class__.__name__ in ['CharField', 'TextField']:
                            q_objects |= Q(**{f"{f.name}__icontains": q})

                    queryset = queryset.filter(q_objects)

            else:
                for f in self.model._meta.get_fields():
                    if f.is_relation and (f.many_to_one or f.one_to_one or f.many_to_many):
                        related_model = f.related_model
                        for related_field in related_model._meta.get_fields():
                            if related_field.__class__.__name__ in ['CharField', 'TextField']:
                                field_name = f"{f.name}__{related_field.name}"
                                q_objects |= Q(**{f"{field_name}__icontains": q})
                    elif f.__class__.__name__ in ['CharField', 'TextField']:
                        q_objects |= Q(**{f"{f.name}__icontains": q})
                queryset = queryset.filter(q_objects)
                
        return queryset
                  
   
            

Related Posts