Django filter on any matching column

in django admin we have search field at the top of the page (right?). If I take example of user model. and search field is there.

search_fields = ('name', 'phone', 'email', 'city')

I get a query_param in GET api. but my program doesn't know what it is. it could be a phone_no or email or name or anything else. I have to search in User model and filter out all rows which contain this data in any of the column.

so I want to write a django query but I'm not sure what is the best optimized way to do this. write now I use Q object and then OR operation. eg Q(phone=param) | Q(email=param) Q(phone=param) | Q(email=param) .

and Iwant to know if i have to write SQL query for this how would I


With ORM you can do no more than chain Q objects. You can try to write your own SQL queries but there is much work to do and you won't accomplish the best possible search also.

If you really want to have fast search that will deal with big amounts of data you need to take a look at haystack. It's a very good django module which makes search easy and fast.


Q object is definitely right. You could do it dynamically like:

from django.db.models import Q

search_fields = ('name', 'phone', 'email', 'city')
q_objs = [Q(**{'%s' % i: param}) for i in search_fields]
queries = reduce(lambda x, y: x | y, q_objs)

results = Model.objects.filter(queries)

You can even do q_objs = [Q(**{'%s__icontains' % i: param}) for i in search_fields] to support incomplete search.

链接地址: http://www.djcxy.com/p/38708.html

上一篇: 在Django中,如何使用动态字段查找过滤QuerySet?

下一篇: Django筛选任何匹配的列