我有一个模型菜和模型菜单:
class MenuItem(models.Model):
dish_name=models.TextField(unique=False)
price=models.DecimalField(max_digits=5,decimal_places=2,blank=True)
main_ngredient=models.TextField(unique=False)
course=models.CharField(max_length=100)
menu=models.ForeignKey('Menu')
def __unicode__(self):
return name
class Menu(models.Model):
restaurant=models.TextField(unique=False)
year=models.IntegerField(unique=False)
location=models.TextField(unique=False)
status=models.CharField(unique=False,max_length=20)
NYPLid=models.IntegerField(unique=True)
def __unicode__(self):
return restaurant
def __period__(self):#adapted from http://stackoverflow.com/questions/2272149/round-to-5or-other-number-in-python
p=int(10*round(float(self.year)/10))
if p < self.year:
return "%s-%s"%(p,p+5)
else:
return "%s-%s"%(p-5,p)
period=property(__period__)
我有一个视图搜索:
def search(request):
errors = []
form = SearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
row = cd['row']
query = cd['query']
dish_row_dict = {"dish_name":'name__icontains=query',
"main_ingredient":"ingredient__icontains=query",
"course":"course__iexact=query"
}
menu_row_dict = {"year":'year__exact=query',
"period":'period__exact=query',
"location":'location__icontains=query',
"restaurant":"restaurant__icontains=query",
}
if row in dish_row_dict:
dishes = MenuItem.objects.filter(eval(dish_row_dict[row]))
elif row in menu_row_dict:
dishes = MenuItem.objects.filter(eval("menu__%s"%(menu_row_dict[row])))
return render_to_response("search_returns.html",{"dishes":dishes})
return render_to_response("search_page.html",{"form":form})
我有一个表单SearchForm:
class SearchForm(forms.Form):
row = forms.ChoiceField([("dish_name","Dish Name"),("year","Year"),
("period","Five-Year Period"),("location","Location"),
("main_ingredient","Main Ingredient"),("course","Course or Dish Type"),("restaurant","Restaurant"),])
query = forms.CharField())
我希望用户能够选择其中一个选项,然后根据他们的选择进行查询(例如,如果他们选择“菜名”,则按菜名搜索。)他们我正在做的方式现在的事情,用字典+ eval()不起作用(我知道,我知道,eval =坏,但我不知道怎么做!)
我觉得这不是异国情调或不寻常的事情,但如果我能在网上找到任何关于它的话,我会被诅咒。我怀疑答案与MultiValueField或类似的东西有关,但我真的不明白如何使这项工作。
非常感谢任何帮助。
答案 0 :(得分:0)
你可以忘记=query
和eval()
部分并简单地构建一个字典,并将其作为kwargs传递:
filter_keys = {
# menuitem queries
"dish_name":'name__icontains',
"main_ingredient": "ingredient__icontains",
"course": "course__iexact",
# menu queries
"year": 'menu__year__exact',
"period": 'menu__period__exact',
"location": 'menu__location__icontains',
"restaurant": "menu__restaurant__icontains",
}
...
if row in filter_keys:
dishes = MenuItem.objects.filter(**{filter_keys[row]: query})
**
是一种将命名参数作为dict传递的Python方法。