django:按成分搜索

时间:2018-12-09 07:17:20

标签: python django django-models django-views

我正在创建一个网站,用户可以在其中搜索食材的食谱,但是我只能通过输入1种食材进行搜索,当我输入多个食材时,搜索将返回空。 正确的搜索将是用户插入多种成分并返回包含这些成分的食谱。 我找不到问题所在:(

这是我的模特。py

class 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'

views.py

from django.shortcuts import render
from .models import Ingredientes, Nomes, Fotos


def 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 个答案:

答案 0 :(得分:0)

首先使用

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