Home > Back-end >  how can i search in django for multiple values like the ( werkstoffbezeichnung and the werkstoffnumm
how can i search in django for multiple values like the ( werkstoffbezeichnung and the werkstoffnumm

Time:12-16

This cod I made only works for one values, when I try to add other one it stops working. how can i fix it?

def search_post(request):
    if request.method == "POST":
        searched = request.POST.get('searched')
        posts = Post.objects.filter(werkstoffnummer=searched)
        posts = Post.objects.filter(werkstoffbezeichnung=searched)
        
        
        
        return render(request, 'Blog/search_post.html', {'searched': searched, 'posts': posts})
    else:
        return render(request, 'Blog/search_post.html', {})

CodePudding user response:

By searching that way, posts will be set to the last QuerySet you define.

You can work with Q objects to make a QuerySet that searches for both fields:

from django.db.models import Q

def search_post(request):
    if request.method == 'POST':
        searched = request.POST.get('searched')
        posts = Post.objects.filter(
            Q(werkstoffnummer=searched) | Q(werkstoffbezeichnung=searched)
        )
        return render(request, 'Blog/search_post.html', {'searched': searched, 'posts': posts})
    else:
        return render(request, 'Blog/search_post.html', {})

CodePudding user response:

The reason for this behavior is posts is overwritten in the call posts = Post.objects.filter(werkstoffbezeichnung=searched) and hence you see only 1 result. Here is one of the approach:

def search_post(request):
    if request.method == "POST":
        searched = request.POST.get('searched')
        posts = Post.objects.filter(werkstoffnummer=searched) | Post.objects.filter(werkstoffbezeichnung=searched)
   
        return render(request, 'Blog/search_post.html', {'searched': searched, 'posts': posts})
    else:
        return render(request, 'Blog/search_post.html', {})

You can refer to this for more details.

  • Related