【发布时间】:2017-10-05 13:47:24
【问题描述】:
所以我试图在我的项目中实现一个 AJAX 搜索表单。
我的模型包含一个Recipe 类和一个通过外键连接到Recipe 的成分类,这样每个食谱都可以有多种成分。
我的数据库中有一个名为 omelet 的食谱条目,其中包含 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)
可能是一个菜鸟问题,但我非常感谢任何帮助,谢谢。
【问题讨论】:
-
我没有删除只是编辑了标题
-
输出会是什么?直到你说出你需要的东西才能纠正代码
-
对不起,您的编辑并没有改善这个问题。
-
我正在寻找煎蛋卷条目,因此输出将是蛋奶 (AND: ('ingredients__ingredient__icontains', 'egg')) (AND: ('ingredients__ingredient__icontains', 'egg'),( 'ingredients__ingredient__icontains', 'milk'))
]>
标签: django django-models django-views django-queryset django-q