I am trying to make app which user can look for few names of one category in the same time. F.e. There are 10 name like mexicola, red rasputin and black magic. And i wish that user can look for mexicola and red rasputin just with writing "mexicola red rasputin" or "red rasputin mexicola black magic" or just "black magic" and so on. But now it works only with one.. i can not find what is wrong.
Here are my views
from django.shortcuts import render
from django.db.models import Q #new
from .models import Recipe
from .models import Ingredient
def drink_list(request):
template = "drinks/drink_list.html"
return render(request, template)
def search_results(besos):
query = besos.GET.get('q')
q = Q()
for queries in query.split():
q = (Q(recipe_name__icontains=queries))
results = Recipe.objects.filter(q)
template = "drinks/search_results.html"
context = {
'results' : results,
}
return render(besos, template, context)
model:
from django.db import models
class Ingredient(models.Model):
ingredient_name = models.CharField(max_length=250)
def __str__(self):
return self.ingredient_name
class Recipe(models.Model):
recipe_name = models.CharField(max_length=250)
preparation = models.CharField(max_length=1000)
ingredients = models.ManyToManyField(Ingredient)
def __str__(self):
return self.recipe_name
When constructing your queryset filter q
, you are overwriting the same instance again and again - you should or-it instead:
for queries in query.split():
q = q | Q(recipe_name__icontains=queries)
In general however, this approach won't be very fast, if your table gets bigger (the query will take a long time)