0

嗨,我有一个 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吗?

非常感谢任何帮助

4

2 回答 2

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
于 2012-11-15T22:21:43.917 回答
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'))
于 2012-11-15T22:37:57.410 回答