سؤال

help please make a selection from the fields "nickname" and "family". in the database have the following table. I do sample the field "nickname" as follows: views.py:

from django.db.models import Q

@login_required 
def friends_search(request):
    search_result = None

    if request.method == 'POST':    
        if request.POST.get('fld_name'):
            try:
                fld_name = request.POST.get('fld_name')
                search_result = UserProfile.objects.filter(Q(nickname__icontains=fld_name))     
                if not search_result:
                    search_result = 'По вашему запросу ничего не найдено.'
            except Exception as exc:
                search_result = 'В данный момент доступ к базе данных невозможен. Попробуйте повторить ваш запрос позже.'   

    t = loader.get_template('friends_search.html')
    c = RequestContext(request, {
        'search_result': search_result,
    }, [custom_proc])   
    return HttpResponse(t.render(c))

the problem is that I need to take a sample at the same time in the fields "nickname", "family". following method does not work:

search_result = UserProfile.objects.filter(Q(nickname__icontains=fld_name), Q(family__icontains=fld_name))  
هل كانت مفيدة؟

المحلول

Revise Complex lookups with Q objects , You should use the OR operator | .

It can look like this:

from django.db.models import Q

@login_required 
def friends_search(request):
    search_result = None

    if request.method == 'POST':    
        if request.POST.get('fld_name'):
            try:
                fld_name = request.POST.get('fld_name')
                q = Q(nickname__icontains=fld_name) | Q(family__icontains=fld_name)
                search_result = UserProfile.objects.filter(q)     
                if not search_result:
                    search_result = 'По вашему запросу ничего не найдено.'
            except Exception as exc:
                search_result = 'В данный момент доступ к базе данных невозможен. Попробуйте повторить ваш запрос позже.'   

    t = loader.get_template('friends_search.html')
    c = RequestContext(request, {
    'search_result': search_result,
}, [custom_proc])   
    return HttpResponse(t.render(c))

نصائح أخرى

If you want to do an AND query, just append filters, like this:

UserProfile.objects.filter(Q(nickname__icontains=fld_name)).filter(Q(family__icontains=fld_name))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top