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

查看:85
本文介绍了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.7.4 节中有记录.,在解包参数列表下.

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

另外,请注意相同的 dict 没有传递到函数中.创建了一个新副本,因此json"不是 kwargs.

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天全站免登陆