Im building an app using Django 1.10 as backend and Angular 2 4.0 for frontend.
Is it possible to create and save a model instance from a JSON data object?
Example: This model:
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
}
I dont want to manually create the model:
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)
Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
Thanks to Django's native support for jsonb , you can get started using JSON data in your web applications without learning all the native Postgres query operators. Next time you need more flexibility in your data model and want to benefit from the strengths of Postgres give jsonb fields a try.
It is used primarily to transmit data between a server and web application, as an alternative to XML. API's, lightweight responses, etc are basic uses for a JSON string.
You could just do,
PartOne.objects.create(**json)
You can use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function.
This is documented on section 4.7.4 of python tutorial., under unpacking argument lists.
Also, note that the same dict is not passed into the function. A new copy is created, so "json" is not kwargs.
You may also want to take a look at modelform_factory
if you want to run more validation on your data or have more control over input. You can also do good stuff like attaching files.
from django.forms.models import modelform_factory
form = modelform_factory(PartOne, fields=('gender', 'gender_na', 'height', 'height_na',))
populated_form = form(data=my_json)
if populated_form.is_valid():
populated_form.save()
else:
# do something, maybe with populated_form.errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With