Django空获取变量

时间:2012-11-15 22:01:56

标签: django django-models django-views

嗨,我有一个ajax调用,它与一个小视图相连:

def get_spans(snow_load, wind_speed, module_length):
    spans = Spans.objects.values_list('span').filter(
        snow=snow_load,
        wind=wind_speed,
        module_length__gte=module_length,
    ).order_by('span')
    try:
        max_span = max(spans)
    except ValueError:
        max_span = 0
    return max_span

def GetSpans(request):
    # get variables from ajax request
    snow_load = request.GET.get('snow_load', None)
    wind_speed = request.GET.get('wind_speed', None)
    module_length = request.GET.get('module_length', None)
    # call get_spans()
    max_span = get_spans(snow_load, wind_speed, module_length)
    # json encode it
    max_span = simplejson.dumps(max_span, cls=DjangoJSONEncoder)
    return HttpResponse(
        max_span,
        mimetype='application/json'
    )

问题是这些get变量中的任何一个都可能是''或小数。我的问题是处理这些问题的最佳方法是什么?如果变量为'',则会出现invalid literal for int() with base 10:错误。我应该用None替换所有空字符串吗?我应该将所有值都转换为float吗?

任何帮助非常感谢

2 个答案:

答案 0 :(得分:1)

在您的函数get_spans中,您可以排除空字段或无字段:

def get_spans(*args, **kwargs):
   my_dict = {}
   for key in kwargs:
      if kwargs[key]:
         my_dict[key] = kwargs[key]
    spans = Spans.objects.values_list('span') \
                         .filter(**my_dict) \
                         .order_by('span')
    #rest of code

将您的get_spans功能称为:

get_spans(snow=snow_load, wind=wind_speed, module_length__gte=module_length)

更优雅

Requires python2.7+

def get_spans(*args, **kwargs):
    my_dict = {key:val for (key, val) in kwargs.iteritems() if val}
    spans = Spans.objects.values_list('span') \
                         .filter(**my_dict) \
                         .order_by('span')
    #rest of code

答案 1 :(得分:1)

django中的过滤器可以链接,因此您可以这样做:

spans = Spans.objects.values_list('span')
if snow_load:
   spans.filter(snow=snow_load)
if wind_speed:
    spans.filter(wind=wind_speed)
if module_length:
    spans.filter(module_length__gte=module_length)

return max(spans.order_by('span'))