Hulk
Hulk

Reputation: 34170

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.

Upvotes: 6

Views: 10949

Answers (3)

redacted
redacted

Reputation: 3959

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>]

Upvotes: 2

Jiaaro
Jiaaro

Reputation: 76898

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

Upvotes: 20

Alasdair
Alasdair

Reputation: 308799

I don't think the filter clause is suited to this kind of search. You might want to check out Haystack.

Upvotes: 4

Related Questions