我是Django的新手。我有客户端应用程序,它将POST请求发送到服务器以在服务器上创建新的Conference对象。 Serverside代码如下所示:
new_conf.date = request.POST['date']
new_conf.name = request.POST['name']
new_conf.languages = request.POST['languages']
new_conf.is_open = request.POST['is_open']
new_conf.place = request.POST['place']
new_conf.recognition_on = request.POST['recognition_on']
有没有办法把它写得更短?是否可以编写一些通用模板以在类似情况下使用?
答案 0 :(得分:5)
您可以在模型中创建ModelForm
表单,并将请求“解压缩”。将数据存入模型实例
# Create a form instance from POST data.
>>> conf_form = ConferenceForm(request.POST)
# Save a new Conference object from the form's data.
>>> new_conf = conf_form.save()
REF。 https://docs.djangoproject.com/es/1.9/topics/forms/modelforms/#the-save-method
或者,对于更多Python通用解决方案,您可以列出所需的密钥并使用setattr
或设置dict中的密钥,如下所示
for key in ['date', 'name', 'languages', ...]:
setattr(new_conf, key, request.POST[key])
# Or if new_conf is a dict-like obj
new_conf[key] = request.POST[key]