如何在django中从QueryDict创建对象? [英] How to create object from QueryDict in django?

查看:169
本文介绍了如何在django中从QueryDict创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的POST请求中有一个QueryDict,我想根据这个命令在数据库中创建一个新的记录。

  QueryDict:{u'phone':[u'Phone'],u'email':[u'Email'],u'full_name':[u't54'],u'skype':[ u'skype']} 

我可以在一个命令中执行吗?
最好的方法是什么?



谢谢

解决方案

p>只要你没有同一个键的多个值,可以执行以下操作:

  values = QueryDict.dict ()

如果值:
YourModel.objects.create(** values)

但是,我强烈地强调建议使用ModelForm来清理帖子中的数据,然后创建对象。


Let's say I got a QueryDict in my POST request, and I'd like to create a new record in database according to this dict.

QueryDict: {u'phone': [u'Phone'], u'email': [u'Email'], u'full_name': [u't54'], u'skype': [u'Skype']}

Can I do it in one command? What's the best way to go?

Thanks

解决方案

As long as you don't have multiple values for the same key, you can do:

values = QueryDict.dict()

if values:
    YourModel.objects.create(**values)

However, I would strongly suggest using a ModelForm to sanitize the data from the post, and then create the object.

这篇关于如何在django中从QueryDict创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆