我有两种型号:
class Recipe(models.Model):
title = models.CharField()
....
class Ingredient(models.Model):
recipe = models.Foreignkey(Recipe, related_name='recipe_ingredients')
name = models.CharField()
...
所以我想做的是按照给定的成分过滤出食谱,我设法做到这一点:view.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()中,但是感觉不对。
您可以使用distinct()来获取不同的对象。
receipes = Receipe.objects.filter(recipe_ingredients__name__icontains=ingredient).distinct()