Hulk Hulk - 1 month ago 7
Python Question

searching all fields in a table in django

How to search all fields in a table in django using filter clause
ex:table.object.filter(any field in the table="sumthing")

Thanks.

Answer

I agree with Alasdair, but the answer to your question is this though:

from django.db.models import CharField
from django.db.models import  Q

fields = [f for f in table._meta.fields if isinstance(f, CharField)]
queries = [Q(**{f.name: SEARCH_TERM}) for f in fields]

qs = Q()
for query in queries:
    qs = qs | query

table.objects.filter(qs)

note: I have not tested this code, but it should get you quite a bit close to your goal

Comments