Django:使用JSON数据创建和保存模型 [英] Django: Create and save a model using JSON data

查看:604
本文介绍了Django:使用JSON数据创建和保存模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.10作为后端以及Angular 2 4.0作为前端来构建应用程序.

Im building an app using Django 1.10 as backend and Angular 2 4.0 for frontend.

是否可以从JSON数据对象创建和保存模型实例?

Is it possible to create and save a model instance from a JSON data object?

示例:此模型:

class PartOne(models.Model):
  gender = models.SmallIntegerField(choices=[(1, "Male"), (2, "Female")])
  gender_na = models.BooleanField(default=False)
  height = models.SmallIntegerField()
  height_na = models.BooleanField(default=False)

JSON:

json = {
'gender': 1,
'gender_na':False,
'height':195,
'height_na':False
}

不要要手动创建模型:

PartOne.objects.create(gender=json['gender'], gender_na=json['gender_na'], height=json['height'], height_na=json['height_na]

我正在寻找一种自动化的解决方案,例如:

Im looking for an automated solution, like this:

PartOne.objects.create_from_json(json)

推荐答案

您可以做到,

PartOne.objects.create(**json)

在调用函数时,可以通过构造关键字参数字典并将其传递给函数来使用** kwargs语法.

You can use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function.

这已记录在python教程的4.a的第7.4节中. ,在解压缩参数列表下.

This is documented on section 4.7.4 of python tutorial., under unpacking argument lists.

此外,请注意,同一字典未传递到函数中.创建了一个新副本,因此"json"不是多余的东西.

Also, note that the same dict is not passed into the function. A new copy is created, so "json" is not kwargs.

这篇关于Django:使用JSON数据创建和保存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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