我正在创建一个网站,用户可以在其中搜索配料的食谱,但我只能通过输入 1 种配料进行搜索,当我输入一种以上时,搜索返回空。 正确的搜索应该是用户插入多种成分并返回包含这些成分的食谱。 我找不到哪里出了问题:(这是我的models.pyclass Fotos(models.Model): id = models.AutoField(primary_key=True) linkfoto = models.ImageField() nomes = models.ForeignKey('Nomes', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'fotos'class Ingredientes(models.Model): id = models.AutoField(primary_key=True) ingrediente = models.TextField() nomes = models.ForeignKey('Nomes', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'ingredientes'class Nomes(models.Model): id = models.AutoField(primary_key=True) # AutoField? nome = models.TextField() class Meta: managed = False db_table = 'nomes'视图.pyfrom django.shortcuts import renderfrom .models import Ingredientes, Nomes, Fotosdef post_list(request): termo_busca = request.GET.get('pesquisa') if termo_busca: a = Ingredientes.objects.all().filter(ingrediente__contains=termo_busca) # a = a.exclude(ingrediente__icontains=termo_busca!=termo_busca) busca = [p.nomes_id for p in a] lista = [] for i in busca: nome = Nomes.objects.get(id=i) ingredientes = Ingredientes.objects.filter(nomes_id__in=[i]) foto = Fotos.objects.get(id=i) lista.append([nome, ingredientes, foto]) else: a = Nomes.objects.all()[:10] cont = len(a) lista = [] for i in range(1, cont): nome = Nomes.objects.get(id=i) ingredientes = Ingredientes.objects.filter(nomes_id__in=[i]) foto = Fotos.objects.get(id=i) lista.append([nome, ingredientes, foto]) return render(request, 'aplicacao/post_list.html', {'lista': lista})
1 回答
慕妹3242003
TA贡献1824条经验 获得超6个赞
首先使用
ingrediente__icontains
因为在你的情况下,“柠檬”和“柠檬”不一样。我猜用户在 html input或textarea中输入搜索词。您需要使用一些规则来限制输入。示例用户必须使用空格分隔成分。请参阅正确的搜索字符串。
柠檬鱼盐 那么在你看来你需要一一获取它的成分。看
if termo_busca:
all_ingred = Ingredientes.objects.all()
searching_ingred = Ingredientes.objects.none()
for one_ingredient in termo_busca.split():
searching_ingred = searching_ingred.union(searching_ingred, all_ingred.filter(ingrediente__icontains=one_ingredient))
# do some with ingredients that match searching
添加回答
举报
0/150
提交
取消