Finding multiple fields of a django model without a third-party application

I have one model in my django application for which I want to create a search form. Is there a way to simultaneously search for all fields in a model with the same search string? I looked at xapian and solr, but they seem to have a lot of overhead for searching on one model. I want to say something like:

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

I understand that it may not be something short, but now the only option I can find, in addition to using the application for search, is to check each field separately and combine the results together.

+3
source share
2 answers

, Q objects kwarg reduce() operator.or_, .

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

, :

django 1.10 SearchVector.

:

, . Entry , tagline. , 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>]
0

Source: https://habr.com/ru/post/1781182/


All Articles