Searchbuilder

Unsure where did I get the base of this code but I like to modify it so it can search in ForeignKey field as well. Simply adding models.ForeignKey not working

if 'all_field' in self.search_field:
                search_fields = [i.name for i in Employee._meta.fields
                                 if 'id' not in i.name and isinstance(i, (models.CharField, models.TextField))]

                q = reduce(or_, [Q(**{'{}__icontains'.format(f): self.search_text}) for f in search_fields], Q())
                queryset = Employee.objects.filter(q).order_by(self.order_by)
                return queryset

When you say you want to “search in ForeignKey field”, are you saying you want to search for the PK of that related object? Or are you really saying that you want to search within fields within that related object?

If the latter, you would need to construct your query element such that it generates the right field reference(s) within the Q object.

dirty but works, basically if a employee have a ForeignKey to a base “Paris” I cant search it because filter need base__city__icontains, other filed like first_name is fine.
The code below changes the filter list if is a ForeignKey
Would be nice to have recursive loop to go deeper in case ForeignKey have a ForeignKey :wink:

if 'all_field' in self.search_field:
                search_fields = list()
                for i in Employee._meta.fields:
                    if 'id' not in i.name and isinstance(i, (models.CharField, models.TextField)):
                        search_fields.append(i.name)
                    elif isinstance(i, (models.ForeignKey)):
                        for j in i.related_model._meta.fields:
                            if 'id' not in j.name and isinstance(j, (models.CharField, models.TextField)):
                                k = i.name + '__' + j.name
                                search_fields.append(k)