How do you deserialize an xml file into a django model, when the xml field names do not match the model field names?
Here is an example XML file:
<?xml version="1.0" encoding="UTF-8"?> <MaterialLot xmlns="http://www.wbf.org/xml/B2MML-V0401"> <ID>B0000</ID> <StorageLocation>Box 1</StorageLocation> </MaterialLot>
Here is the django model:
class MaterialLot(models.Model): material_lot_id = models.CharField(max_length=MAX_LEN_ID, unique=True) storage_location = models.CharField(max_length=MAX_LEN_LOC, blank=True)
And here is the serializer built using the django_rest framework:
class MaterialLotSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MaterialLot fields = ('material_lot_id', 'storage_location')
The problem:
I can not create a MaterialLot model field called 'ID' as ID is reserved for the model primary key. Hence, I need to map the XML 'ID' field to the 'material_lot_id' MaterialLot model field.
Ultimately, I want to read data from an XML file, and save the data in a django model:
with open(file_path, 'r') as f: xmlstring = f.read() stream = BytesIO(xmlstring) data = XMLParser().parse(stream) serializer = MaterialLotSerializer(data=data) serializer.is_valid() serializer.save()
No comments:
Post a Comment