关键字参数/字典

问题描述:

在Django应用程序中,我有一个函数接受请求并解析返回结果字典的参数。关键字参数/字典

例如,这样的事情:

def parse_event_parameters(request): 
    """ 
    Parse the parameters for a given event 
    from a request and return the result 
    as a dictionary of strings. 
    """ 
    try: 
     request_params = { 
      'event_id': id, 
      'start_date': request.POST[id + '_start_date'], 
      'end_date': request.POST[id + '_end_date'], 
      'shift_type': request.POST[id + '_shift_type'], 
      'rec_type': request.POST[id + '_rec_type'], 
      'event_length': request.POST[id + '_event_length'], 
      'event_pid': request.POST[id + '_event_pid'], 
     } 
    except KeyError, err: 
     raise err 
    return request_params 

我然后传送字典的方法我的模型内创建或更新有关的事件。

super(Event, self).update(event_id, start_date, 
      end_date, shift_type, rec_type, 
      event_length, event_pid, employee_id) 

超类基本验证请求的值,并将其保存到模型:

e.update(**parameters) 

一旦出现,如下更新方法调用父类。现在,我需要在我的模型中添加另一列,并需要更新每种方法。

我对Django相当陌生,但这看起来并不像最干净的方法。

有没有更优雅的方法来处理这个问题? 我应该让字典通过每种方法,而不是打扰拆包它?

+0

我觉得这将是更适合于[代码审查(HTTP://codereview.stackexchange .com /),因为你在谈论工作代码和风格。 – 2013-03-15 13:29:31

听起来你应该使用ModelForms:

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelform

一般来讲,只要你与请求数据处理(POST或GET或其他),你应该考虑使用表单验证。一个常见的误解是,Django表单仅用于显示实际的HTML表单,但实际情况是它是一种数据验证API,可以在许多情况下使用。 ModelForm更进一步,将Django表单绑定到模型类,并负责创建或更新模型(当您在表单上调用save()时)。

然后,一旦你了解ModelForms,考虑寻找到Django的通用视图创建和更新型号:

https://docs.djangoproject.com/en/1.5/topics/class-based-views/generic-editing/