[Answer]-Django modelfield to put in data recursively while iterating over xml tags

1👍

You need to create and save your instances within the loop; you are only assigning values in the loop in your example.

for el in tree.iter():
    ws = olWS()
    ws.country = el.text if el.tag == 'custom_var4' else ''
    ws.comment = el.text if el.tag == 'comments' else ''
    ws.save()

0👍

you need to do one model instance for each row, but as the elements doest seem to be children to a object node but flat list, you can save both values to a dict and then save a model once both are set.

👤krs

0👍

Assuming you have order of 'custom_var_4' and 'comments' elements fixed in XML and both are present , you can improve your code as:

>>> for el in tree.iter():
...     if el.tag=='cusotm_var4':
...         ws.country=el.text
...     if el.tag=='comments':
...         ws.comment=el.text
...         ws.save()

Note: ws.save() in second if.

Disclaimer: you need to take care for aberrations like only one element is present etc.

👤Rohan

Leave a comment