通过select更改查询参数 [英] Change query parameter via select

查看:172
本文介绍了通过select更改查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型菜盘和模型菜单:

I have a model Dish and a model Menu:

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 :

I have a 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 =坏,但我不是确定如何做到这一点!)

I'd like users to be able to choose one of the select options, and then do a query based on their choice (e.g., search by dish name if they select "Dish Name".) They way I'm doing things now, with a dictionary+eval() isn't working (I know, I know, eval = bad, but I wasn't sure how else to do it!)

我觉得像这不是一个异国情调或不寻常的事情,但如果我可以在网上找到任何内容,我会被诅咒的。我怀疑答案与MultiValueField或类似的东西有关,但我真的不明白如何做这个工作。

I feel like this isn't an exotic or uncommon thing, but I'll be damned if I can find anything about it online. I suspect the answer has something to do with MultiValueField or something like that, but I really don't understand how to make that work.

任何帮助将不胜感激。

Any help would be greatly appreciated.

推荐答案

您可以忘记 =查询 eval()部分,只需构建一个dict,并将其作为kwargs传递:

You can forget the =query and the eval() part and simply build a dict, and pass it as 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})

** 是一个Python passi的方式ng命名参数为dict。

The ** is a Python way of passing named parameters as a dict.

这篇关于通过select更改查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆