How to search all fields in a table in django using filter clause ex:table.object.filter(any field in the table="sumthing")
Thanks.
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
I don't think the filter clause is suited to this kind of search. You might want to check out Haystack.
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>]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With