Question

I have a row/s of fields being posted in a view with their names numbered per each row, e.g. 01_field1, 01_field2, 02_field1, 02_field2 etc. The user can add and remove rows, so I won't know how many rows are posted. In other words, I want to be able to group the post key and values by their row number.

Here is an example of what is being posted i.e. the value of 'items'

[('01_cost', 'value'), ('01_date_end', 'value'), ('01_date_start', 'value'), ('01_hours', 'value'), ('01_resource', 'value'), ('01_task_desc', 'value'), ('02_cost', 'value'), ('02_date_end', 'value'), ('02_date_start', 'value'), ('02_hours', 'value'), ('02_resource', 'value'), ('02_task_desc', 'value'), ('job_description', 'value'), ('job_number', 'value')]

I am trying to loop though the sorted post items and insert into MongoDB in the following nested format:

{
    "row1": {
                "01_field1": "value", 
                "01_field2": "value"
            },
    "row2": {
                "02_field1": "value", 
                "02_field2": "value"
            },
}

I am currently trying to generate a list of dicts for each row, but this doesn't appear to be inserting into mongo as above. Here is the (not working) code I currently have.

items = sorted(request.POST.items())

project_data = []
d = {}
etid = '01'

for key, value in items:
    #get the number from each posted field name
    tid = re.findall(r'\d+', key)

    if etid == tid:
        d.update({key:value})
    else:
        project_data.append(d)
    etid = tid

project_id = project.insert(project_data)
Was it helpful?

Solution

Probably simply changing the following things could work :

project_data = []

=>

project_data = {}

And

else:
    project_data.append(d)

to

else:
    d = {}
    project_data['row' + str(tid] = d

This should get you a structure closer to what you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top