Python, Convert String Into List of Dictionaries, Insert One Dictionary Into Django Model

时间:2018-03-23 00:19:14

标签: django dictionary model

I have the following string received from an ajax post in a django view (its 2 rows of a angular ui-grid):

data=[{"part_name":"33029191913","id":"5","qty":"3","ticket":"","comments":"test"},
{"part_name":"3302919777","id":"3","qty":"323","ticket":"","comments":"test"}]

Then doing json.loads(data) that gives me the following:

data={'part_name': '33029191913', 'id': '5', 'qty': '3', 'ticket': '', 'comments': 'test'}
{'part_name': '3302919777', 'id': '3', 'qty': '323', 'ticket': '', 'comments': 'test'}

Without specifying each field in order to create a dictionary, I want to create one that looks like the following in order to insert it into my model, via MyModel(**data):

{'part_name': '33029191913', 'id': '5', 'qty': '3', 'ticket': '', 'comments': 'test'}

After json.loads(data), if i try to access one element (eg. data[0]['part_name']), it correctly shows '33029191913', but if I do data[0] or data[1], it gives me only the apparent keys: part_nameidqtyticketcomments.

How can I separate the string received by ajax into dictionaries in order to insert them into the django model?

2 个答案:

答案 0 :(得分:0)

假设你在变量for datain my_json_data: MyModel.objects.create(**data) 中列出了dict值,那么试试这个

MyModel(**kwargs)


如果我没有错MyModel无法在数据库中创建对象,它只会初始化对象

注意:dict的键必须与O(n)类中的字段名相同

UPDATE-1
在Django中有一个方法,bulk_create可能对您的上下文有用(但是,您需要创建一个至少具有mymodel_list = [MyModel(**data) for data in my_json_data] MyModel.objects.bulk_create(**mymodel_list) 复杂度的列表

public static function save_settings_fields(){

    $myArray = json_decode($_POST['to_save']);
    wp_send_json(var_dump($_POST['to_save']));

    //i can't even get to this point.
    $saved_content = json_decode($_POST['to_save']);
    $post_id = $saved_content['post_id'];
    $this_count = (int)$saved_content['index'];
    $foobar = new POB_Save_Settings;
    $isdone = $foobar->update_static_content($post_id, $this_count, $saved_content);
    if ( is_wp_error( $isdone ) ) {

        wp_send_json_error( $isdone );

    } else {
      wp_send_json( $isdone );
    }
  }

答案 1 :(得分:0)

从帖子中取出这个json字符串:

data=[{"part_name": "part 1", "part_id": "1", "quantity": "233", "ticket": "32", "comments": "32"}{"part_name": "part 1", "part_id": "1", "quantity": "233", "ticket": "32", "comments": "32"}]

grid = ast.literal_eval(data)返回:

{'part_name': 'part 1', 'part_id': '1', 'quantity': '233', 'ticket': '32', 'comments': '32'}{'part_name': 'part 1', 'part_id': '1', 'quantity': '233', 'ticket': '32', 'comments': '32'}

假设ajax json字符串上的键与模型字段相同(只有' part_name'字段不在模型中,并且硬编码order_id外键用于测试目的):

    for d in grid:
        object_insert={}
        for key in d:
            object_insert[key]=d[key]
            object_insert['order_id']=1
        del object_insert['part_name']
        order=Order_Detail(**object_insert)
        order.save()

这样可以在模型中保存字典,而无需指定每个键。