Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching all fields in a table in django

Tags:

python

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.

like image 249
Hulk Avatar asked Dec 08 '09 13:12

Hulk


3 Answers

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

like image 162
Jiaaro Avatar answered Nov 19 '22 12:11

Jiaaro


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

like image 43
Alasdair Avatar answered Nov 19 '22 10:11

Alasdair


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>]
like image 1
redacted Avatar answered Nov 19 '22 10:11

redacted