I got a serach box in my project, the thing is that a user can enter any keyword and my ModelForm filters the fields I explicitly tell to filter, I use the following piece of code in my Form:
def get_matching_siniestros(self):
if self.cleaned_data['keywords'] is None:
return None
matching = []
for kw in self.cleaned_data['keywords']:
numero_ajuste = Siniestro.objects.filter(
numero_ajuste__icontains=kw
)
nombre_contratante = Siniestro.objects.filter(
poliza__contratante__nombre__icontains=kw
)
matching = chain(
numero_ajuste,
nombre_contratante,
matching
)
# verify not repeated Siniestro
non_rep_siniestros = []
for siniestro in matching:
if siniestro not in non_rep_siniestros:
non_rep_siniestros.append(siniestro)
return non_rep_siniestros
What I want to do is to programatically filter on any CharField in the Model and also if possible on any CharField of nested relations, in this example Siniestro has a FK to poliza and poliza has an FK to contratante.
You can iterate over every field and do whatever you like, e.g.:
where process can be a function, or whatever you require.
That said, I should really point out that the complexity you’re trying to involve is bound to get messy. IMO, have a look at django-haystack. Indexing should be the way to go.