Reputation: 125
I want to create a search panel. There will be many fields to fill out and if user doesn't fill out something I want to select all records from database for this parameter.
And I am wondering how to do this in django model ? In raw MySQL that'd be ease, but I don't now how to set up conditions, for example ,
if user filled out field Name select only this choice, if not, select all
Are there best practices for this kind of problem ?
Thanks in advance,
Upvotes: 1
Views: 3931
Reputation: 2357
Lets take the example of Blogpost
project where i have a index.html
page to render my data by using. So to search in that data i will use Field lookups.
In this BlogView
you can see i specify query
, where if we get q
in request it means query
is not empty so it will run the Filter
method where using icontains
i can ask specify what to lookup e.g title in my case.
Don't forget to use Double-Underscore __
, also referred as dunder
def BlogView(request):
query = request.GET.get("q", None)
blog = PostModel.objects.all()
if query is not None:
blog = blog.filter(
Q(title__icontains=query) |
Q(content__icontains=query)
)
context = {
"queryset": blog,
}
template = 'blog/index.html'
return render(request, template, context)
Upvotes: 3
Reputation: 3120
You can achive this by creating dynamic field lookups with Q
shown as below:
from django.db.models import Q
# queryets are lazy. So does not hit do db
queryset = MyModel.objects.all()
query = Q()
for field_name, value in request.POST.items():
if value:
try:
MyModel.get_field(field_name)
except:
# Field does not exist on model
continue
lookup = "{}__icontains".format(field_name)
query |= Q(**{lookup: value})
# query &= Q(**{lookup: value})
queryset = queryset.filter(query)
Upvotes: 0
Reputation: 5720
I think you should look at django-filter package, use this module to provide your search fields
Upvotes: 1