简体   繁体   中英

Save django models to XML

I have this django view code that saves my django model to xml file.

def my_serialize(request):
    from django.core import serializers
    data = serializers.serialize("xml", LogChanges.objects.all())
    from django.core.files import File
    f = open('tickets.xml', 'w')
    myfile = File(f)
    myfile.write(data)
    myfile.close()
    return HttpResponse("All done!")

Then I get the output this way:

<django-objects version="1.0">
    <object pk="1" model="ticket.logchanges">
        <field type="CharField" name="prevRemarks">action taken</field>
        <field type="IntegerField" name="idTicket">1</field>
        <field type="DateTimeField" name="dateChanged">2015-09-05</field>
        <field type="CharField" name="status">Open</field>
        <field type="CharField" name="userID">admin</field>
    </object>
</django-objects

Is there a way that I can save this in a simpler form of xml, without using a library, or do I really have to use a library? Like:

<rowset> 
    <row>
        <prevRemarks> action taken </prevRemarks>
        <idTicket>1</idTicket>
        ...etc...
    </row>
</rowset>

It looks like the XML renderer plugin for Django Rest Framework might suit your preferences a bit better.

Sample output for User model:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <list-item>
        <id>1</id>
        <username>jpadilla</username>
        <email>jpadilla@example.com</email>
        <is_staff>True</is_staff>
    </list-item>
</root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM