Search through multiple fields in Django

送分小仙女□ 提交于 2019-11-30 21:20:43

you can use django Q objects to do OR query,

or if you want to ANDyour queries together just use the current lookups as kwargs

seens=Finhall.objects.filter(name__icontains=query_string, address__icontains=query_string)

You should really consider full text search or haystack (which makes search easy) because icontains issues a %LIKE% which is not remotely scalable

EDIT: Just noticed it is Postgres only

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

To search same text in multiple fields you can use this :

from django.db.models import Q

class SearchAPI(APIView):
    def get(self, request, search_text, format=None, **kwargs):
        Model.objects.filter(Q(search_tags__contains=search_text) | Q(auto_tags__contains=search_text)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!