我正在开发一个django应用程序,我可以根据食谱过滤成分。我正在使用django过滤器来为我的用户提供过滤选项。我的过滤下拉工作完全正常,但我想在提交时添加一个选项,所有成分应该列出,无论他们的食谱如何。
这是我的代码:
#models.py
class Recipe(models.Model):
user = models.ForeignKey('auth.User')
title = models.CharField(max_length=500)
description = models.TextField(max_length=500)
rules = models.TextField(max_length=500,blank=True)
def __str__(self):
return self.title
class Ingredient(models.Model):
user = models.ForeignKey('auth.User')
recipe_id = models.ForeignKey(Recipe, on_delete=models.CASCADE)
title = models.CharField(max_length=500)
instructions = models.CharField(max_length=500)
rules = models.TextField(max_length=500,blank=True)
primal = models.CharField(default='0',max_length=500,blank=True)
def __str__(self):
return self.title
#forms.py
class RecipeFilter(django_filters.FilterSet):
class Meta:
model = Ingredient
fields = ['recipe_id']
#views.py
def ingredient_list(request):
ingredientfilter = IngredientFilter( queryset=Recipe.objects.filter(user = request.user))
if request.method == 'GET' and 'recipe_id' in request.GET:
recipe_id=request.GET['recipe_id'];
ingredients = Ingredient.objects.filter(recipe_id= recipe_id)
selected_combo_value = Recipe.objects.get(pk=recipe_id)
return render(request, 'ingredient_list.html',{'ingredients':ingredients, 'ingredientfilter': ingredientfilter,'selected_combo_value':selected_combo_value })
else:
ingredients = Ingredient.objects.filter(user = request.user)
return render(request, 'ingredient_list.html',{'ingredients':ingredients, 'ingredientfilter': ingredientfilter })
知道该怎么做吗?
答案 0 :(得分:0)
这是一个众所周知的issue。解决方法是覆盖过滤器的选项。
class RecipeFilter(django_filters.FilterSet):
def __init__(self, *args, **kwargs):
super(RecipeFilter, self).__init__(*args, **kwargs)
self.filters['recipe_id'].field.choices.insert(0, ('', u'---------'))