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.
Solution 1:
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 ifisinstance(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
Solution 2:
I don't think the filter clause is suited to this kind of search. You might want to check out Haystack.
Solution 3:
EDIT: Just noticed this is limited to Postgres
Ancient question, but for further reference:
Apparently in django 1.10 SearchVector class was added.
Usage from the docs:
Searching against a single field is great but rather limiting. The Entry instances we’re searching belong to a Blog, which has a tagline field. To query against both fields, use a SearchVector:
>>>from django.contrib.postgres.search import SearchVector>>>Entry.objects.annotate(... search=SearchVector('body_text', 'blog__tagline'),...).filter(search='Cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
Post a Comment for "Searching All Fields In A Table In Django"