【问题标题】:Filtering on foreignkey django过滤外键django
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 1970-01-01
      • 2018-01-05
      • 2013-09-05
      • 2016-07-12
      • 2013-09-04
      • 2021-01-26
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多