【发布时间】:2020-09-07 19:03:13
【问题描述】:
我有两个模型:
class Recipe(models.Model):
title = models.CharField()
....
class Ingredient(models.Model):
recipe = models.Foreignkey(Recipe, related_name='recipe_ingredients')
name = models.CharField()
...
所以我想做的是按给定成分过滤掉食谱,我设法做到了这一点: 视图.py
class SearchResultListViewIngredient(ListView):
model = Recipe
paginate_by = 25
template_name = 'recipes/search_ingredient.html'
def get_queryset(self):
"""
Filter out recipes by given ingredient
"""
ingredient = self.request.GET.get('ingredient')
object_list = []
if ingredient:
i = Ingredient.objects.filter(name__icontains=ingredient)
object_list = [r.recipe for r in i]
return object_list
这样做的问题是,如果它们是多个具有相同名称的成分,它会返回重复的对象。 例如,一个以鸡蛋和茄子为原料的食谱。该对象在过滤后会出现两次。有没有更好的方法来做这个过滤器?
提前致谢。
编辑: 我知道我可以将 object_list 包装在 set() 中,但感觉不对。
【问题讨论】:
标签: django django-models filter django-queryset