Django - Django search post using view function
Using filter() is powerful and it's even possible to chain filters together. However often you'll want more complex lookups such as using "OR" which is when it's time to turn to Q objects. Here's an example where we set the filter. It's as simple as importing Q at the top of the file and then subtly tweaking our existing query.
myapp/views.py
from django. shortcuts import render
from models import Post
from django.db. models import Q # New
def index(request):
search_post = request.GET.get('search')
if search_post:
posts = Post.objects.filter(Q(title__icontains=search_post) & (content_icontains=search_post))
else:
# If not searched, return default posts
posts = Post.objects.all().order_by("-date _created")
return render(request, 'myapp/index.htmI', {'posts': posts})
For more detail about this, you can read in learndjango.com blog here: https://learndjango.com/tutorials/django-search-tutorial
Related Post
There are no posts related to this blog!