How do I create a query which filters a model like this?
My model is:
class test(models.Model):
name = models.CharField(max_length=50)
status = models.CharField(max_length=50)
other = models.CharField(max_length=50)
I would like such that instead of OR I filter the query by AND. I have tried changing the | to & but it does not work. To make it more complex, if I have filters on the template as a form such that:
Filter By Name: DropDownList of Names
Filter By Status: DropDownList of Statuses
Filter By Other: DropDownList of Others
If I choose name1, status1 and other1 from the drop down boxes it should display the results of:
results = test.objects.filter(name=name1,status=status1,other=other1)
Here is my current query in views.py:
def search(request):
query = request.GET.get('q', '')
if query:
qset = (
Q(name__icontains=query) |
Q(status__icontains=query) |
Q(other__icontains=query)
)
results = test.objects.filter(qset).distinct()
else:
results = []
return render_to_response("test/search.html", {
"results": results,
"query": query
})
This currently only searches name, status or other. If I change the | to & it searches for all of them but nothing shows when I display results because the query processing from the form drop down boxes are not linked. How to link them? How to also have an ALL option for the drop downs for the specific field?
I hope I have made this clear. Thank you.
I recommend you take a look django-filters application. It can automatize all routine with form dropdowns and making querysets by the search/filter query: