Matt Phillips
Matt Phillips

Reputation: 11499

Search multiple fields of django model without 3rd party app

I have a single model in my django app that I want to create a search form for. Is there a way to search all the fields in the model at once with the same search string? I've looked into xapian and solr but they seem like a lot of overhead for searching over 1 model. I want to be able to say something like:

results = Assignment.objects.filter(any_column = search_string)

I realize there might not be something that concise but right now the only option I can come up with other than using a search app is to check each field separately and concatenate the results together.

Upvotes: 3

Views: 3774

Answers (2)

redacted
redacted

Reputation: 3959

Old question, but for further reference I am adding this:

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: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Once you have all the field names you can create Q objects using kwarg expansion and use reduce() along with operator.or_ to turn them into a single query.

qgroup = reduce(operator.or_, (Q(**{fieldname: value}) for fieldname in fieldnames))
asgns = Assignment.objects.filter(qgroup)

Upvotes: 13

Related Questions