[Fixed]-Generate XML file from model data


You have two possible solutions here:


You can extend base django xml serializer(django.core.serializers.xml_serializer.Serializer) and modify it so it will return data in your structure. You could then run ex.

YourSerializer('xml', myModel.objects.filter(instanceIwantTowrite), fields=('fieldName'))

and it will output data in your structure.


Write simple function that will render template with your data structure and return xml data in your format:

Python code

from django.template.loader import render_to_string

def my_serialize(query_set):
    xml = render_to_string('xml_template.xml', {'query_set': query_set})

    return xml

Template xml_template.xml

<?xml version="1.0" encoding="UTF-8"?>
     {% for object in query_set %}
     <textField id="{{ object.pk }}" text="{{ object.my_field }}" />
     {% endfor %}


For a more generic approach to solving this problem, you can avoid templates by using a simple duck punch on Models, and serialize any deep object graph to XML using ElementTree.

Here’s how I solved it:

Monkey patch/duck punch models in your Model.py like:

if hasattr(models.Model, "to_element")==False:
    import xml.etree.ElementTree as ET
    def to_element(self):
        ele = ET.Element(self.__class__.__name__)
        for field in self._meta.fields:
        return ele
    models.Model.to_element = to_element

This adds a method to Model which creates an Element instance containing the fields from the model that you care about, without the django cruft.

Then, to construct your xml document, just do this:

dealer = Dealer.objects.get(id=dealer_id)
makes = DealerMake.objects.filter(dealer=dealer)

root = dealer.to_element()
for make in makes:

xml = ET.tostring(root)
print xml

With this approach you can get a nicely formatted xml document with all django model fields as attributes, and construct an n-level deep hierarchy. Each xml node will be named the same as the model class.

Leave a comment