过滤外键django

Filtering on foreignkey django

我有两个模型:

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

问题是它 returns 复制对象,如果它们不止是一种同名成分。 因此,例如,以鸡蛋和茄子为原料的食谱。这个对象在过滤后会出现两次。有没有更好的方法来执行此过滤器?

提前致谢。

编辑: 我知道我可以将 object_list 包装在 set() 中,但感觉不对。

您可以使用 distinct() 来获取不同的对象。

recipes = Recipe.objects.filter(recipe_ingredients__name__icontains=ingredient).distinct()