Django Q AND lookup - 查询复杂查找中的多个条目

时间:2017-05-07 14:32:23

标签: django django-models django-views django-queryset django-q

所以我试图在我的项目中实现一个AJAX搜索表单。

我的模型包含一个食谱类和一个通过外键连接到食谱的成分类,这样每个食谱可以有几种成分。

我的数据库中有一个食谱条目,标题为煎蛋卷,含有2种成分 - 鸡蛋和牛奶。

我的查询如下:

for title_ing in search_text:
    recipe_list_search = recipe_list_search & (Q(ingredients__ingredient__icontains=title_ing))

当分别搜索每种成分时,我得到正确的回报,例如,我的蛋的输出:

egg
(AND: ('ingredients__ingredient__icontains', 'egg'))
<QuerySet [<Recipe: Eggs>, <Recipe: omlet>, <Recipe: Pan Egg>]>

或牛奶:

milk
(AND: ('ingredients__ingredient__icontains', 'milk'))
<QuerySet [<Recipe: sdfsd>, <Recipe: omlet>]>

但是,当搜索两种成分时,我得到以下输出:

egg milk
(AND: ('ingredients__ingredient__icontains', 'egg'))
(AND: ('ingredients__ingredient__icontains', 'egg'),('ingredients__ingredient__icontains', 'milk'))
<QuerySet []>

因此查询不会返回包含两个成分的条目 知道为什么会这样吗?

我的模型的代码:

class Ingredient(models.Model):
recipe = models.ForeignKey("Recipe", verbose_name=_("Recipe"), related_name="ingredients", on_delete=models.CASCADE)
quantity = models.CharField(_("Quantity"), max_length=10, blank=True, null=True)
unit = models.CharField(_("Unit"), choices=fields.UNITS, blank=True, null=True, max_length=20)
ingredient = models.CharField(_("Ingredient"), max_length=100)
note = models.CharField(_("Note"), max_length=200, blank=True, null=True)

def __str__(self):
    _ingredient = '%s' % self.ingredient

    if self.unit:
        _ingredient = '%s %s' % (self.get_unit_display(), _ingredient)

    if self.quantity:
        _ingredient = '%s %s' % (self.quantity, _ingredient)
    #python anywhere doesnt register len for somereason so should be changed
    if len(self.note):
       _ingredient = '%s - %s' % (_ingredient, self.note)

    return _ingredient

class Meta:
    verbose_name = _("Ingredient")
    verbose_name_plural = _("Ingredients")

和视图:

def search(request):
if request.method == "POST":
    search_text = request.POST['search_text']
else:
    search_text = ''

recipe_list_search = ''
print(search_text)
search_text = search_text.split()

recipe_list_search = Q()
for title_ing in search_text:
    recipe_list_search = recipe_list_search & (Q(ingredients__ingredient__icontains=title_ing))
    print(recipe_list_search)
f_search=Recipe.objects.filter(recipe_list_search).distinct()
print(f_search)
context = {'recipe_list_search': f_search}
return render(request, 'stage9/ajax_search.html', context)

可能是一个菜鸟问题,但我非常感谢任何帮助,谢谢。

0 个答案:

没有答案