Django:从GET请求生成查询集 [英] Django: Generating a queryset from a GET request
本文介绍了Django:从GET请求生成查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def search_items(request):
如果请求中为'search_name' .GET:
query_attributes = {}
query_attributes ['color'] = request.GET.get('color','')
如果不是query_attributes ['color' ]:del query_attributes ['color']
query_attributes ['shape'] = request.GET.get('shape','')
如果不是query_attributes ['shape']: del query_attributes ['shape']
items = Items.objects.filter(** query_attributes)
但我很确定有一个更好的方法来解决它。
解决方案
你可以做到与列表comp和感兴趣的参数设置:
def search_items(请求):
如果'search_name'在请求中.GET:
interest_params =('color','shape')
query_attrs = dict([(par ()
$ b items = Items.objects.filter(** query_attrs)
只是为了好玩(也不实际上这样做),你可以一行:
def search_items(request):
items = Items.objects.filter(
** dict([(param ,val)for param,val in request.GET.iteritems()
如果param in('color','shape')和val])
)if'search_name'在request.GET其他无
I have a Django form setup using GET method. Each value corresponds to attributes of a Django model. What would be the most elegant way to generate the query? Currently this is what I do in the view:
def search_items(request):
if 'search_name' in request.GET:
query_attributes = {}
query_attributes['color'] = request.GET.get('color', '')
if not query_attributes['color']: del query_attributes['color']
query_attributes['shape'] = request.GET.get('shape', '')
if not query_attributes['shape']: del query_attributes['shape']
items = Items.objects.filter(**query_attributes)
But I'm pretty sure there's a better way to go about it.
解决方案
You could do it with a list comp and and "interested params" set:
def search_items(request):
if 'search_name' in request.GET:
interested_params = ('color', 'shape')
query_attrs = dict([(param, val) for param, val in request.GET.iteritems()
if param in interested_params and val])
items = Items.objects.filter(**query_attrs)
Just for fun (aka don't actually do this) you could do it in one line:
def search_items(request):
items = Items.objects.filter(
**dict([(param, val) for param, val in request.GET.iteritems()
if param in ('color', 'shape') and val])
) if 'search_name' in request.GET else None
这篇关于Django:从GET请求生成查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文