Wildcard searching in Django

蓝咒 提交于 2019-12-11 08:57:09

问题


How can we do a wildcard searching in Django. If i am filtering username from a list in database, how is it possible to display the filtered data with those exact usernames or part of it.?

def filter(request):
    val3='' 
    if request.GET.has_key('choices'):
        val2=request.GET.get('choices')
    if request.GET.has_key('textField'):
        val3=request.GET.get('textField')
    if request.POST:
        val2=request.POST.get('choices')    
        val3=request.POST.get('textField')
    if val2=='Designation':                
        newData = EmployeeDetails.objects.filter(designation=val3) 
        flag=True 
    elif val2=='Name':
        newData = EmployeeDetails.objects.filter(userName=val3)
        flag=True 
    elif val2=='EmployeeID':
        newData = EmployeeDetails.objects.filter(employeeID=val3)  
        flag=True       
    elif val2=='Project':
        newData = EmployeeDetails.objects.filter(project=val3)   
        flag=True   
    elif val2=='DateOfJoin':
        newData = EmployeeDetails.objects.filter(dateOfJoin=val3) 
        flag=True       
    else:
        return HttpResponseRedirect('/employeeList/')

This is my function for filtering. Now its filtering with exact words. I want to display the userNames even if part of it is given for filtering. Please help me to solve this as i am new with Django


回答1:


Try using a less strict filter, like __contains:

elif val2=='Name':
        newData = EmployeeDetails.objects.filter(userName__contains=val3)
        flag=True 

Docs: http://docs.djangoproject.com/en/dev/ref/models/querysets/#contains




回答2:


You can use contains query e.g.

Entry.objects.get(headline__contains='Lennon')

See http://docs.djangoproject.com/en/dev/ref/models/querysets/#contains

There are other options too like startswith, endswith, and you can do even regex search on most databases.




回答3:


Probably field lookups will help you here. It lets to filter by beginning of the word, containing word and so on.



来源:https://stackoverflow.com/questions/5230200/wildcard-searching-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!