简体   繁体   中英

how can i search in django for multiple values like the ( werkstoffbezeichnung and the werkstoffnummer )

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', {})

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', {})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM