Reputation: 571
I got a a Database with a few columns. I want to add to my search the option to search not only one column like Project. I want to search a few more columns too.. so the search will look for Project or ServerName or IP and search all of the columns or a few of them.
I tried (Project__icontains=query, ServerName__icontains=query) but it said wrong syntax.
index.html:
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
if query:
posts = serverlist.objects.filter(Project__icontains=query)
else:
posts = serverlist.objects.all()
# else:
models.py:
from django.db import models
class serverlist(models.Model):
ServerName = models.CharField(max_length = 30)
Owner = models.CharField(max_length = 50)
Project = models.CharField(max_length = 30)
Description = models.CharField(max_length = 255)
IP = models.CharField(max_length = 30)
ILO = models.CharField(max_length = 30)
Rack = models.CharField(max_length = 30)
Status = models.CharField(max_length = 30)
Upvotes: 1
Views: 306
Reputation:
You could use Q objects
from the docs:
A Q object (django.db.models.Q) is an object used to encapsulate a collection of keyword arguments. These keyword arguments are specified as in “Field lookups” above.
an example:
posts = serverlist.objects.filter(
Q(Project__icontains=query)|Q(ServerName__icontains=query)
)
Upvotes: 2