Reputation: 131
In my Django application, I need to write JSon coming from front end into tables in models.py. The first step to do this, would be convert that Json to dictionary. My question is how to write that dictionary directly to models.py tables? What if some of the fields should be written to one table and some fields should be written to any other table? Is it possible or there is another solution for this? Kindly suggest solutions.
There are two tables in models.py called as chart and columnChart , chart_name and chart_description should be written to chart table whereas x_axis_mapping and y_axis_mapping should be written to columnChart table. All the fields are received in one object called json_data. json_data can be converted to dictionary. So what is the next step?
Thanks in advance.
Upvotes: 2
Views: 120
Reputation: 6112
A simple way to write directly a dictionary into a Model's table is using python's expansion with django ORM
Ex:
myitems = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
mymodel = MyModel(**myitems)
mymodel.save()
For multiple models/tables you can easily filter dictionary and then use it in specific model/table.
Ex:
myitems1 = dict((k,myitems[k]) for k in ('key1',) if k in myitems)
mymodel1 = MyModel1(**myitems1)
mymodel1.save()
myitems2 = dict((k,myitems[k]) for k in ('key2', 'key3') if k in myitems)
mymodel2 = MyModel2(**myitems2)
mymodel2.save()
Upvotes: 2
Reputation: 280
I would suggest looking into http://www.django-rest-framework.org/
The framework handles serializing, deserializing, and dealing with various input types as well as building RESTful API's. The serializers also follow Django's DRY philosophy.
Upvotes: 2