4

How can i create a xml file in django where the file is to contain objects from a queryset?

def my_serialize(request):
    from django.core import serializers
    data = serializers.serialize('xml', Student.objects.filter(Q(name__startswith='A')), 
            fields=('name','dob'))
    from django.core.files import File
    f = open('content.xml', 'w')
    myfile = File(f)
    myfile.write(data)
    myfile.close()

After i call the above function, my content file remains empty, there is no data that gets written in it.

2
  • 1
    You don't create XML files in Django. You create XML files in Python. Commented May 3, 2011 at 9:35
  • Is your file empty because 'data' is empty? Or because file writing is failing? Run this from the django shell and investigate if the serializer call is returning XML. And if the query is returning any objects... Commented May 3, 2011 at 17:31

2 Answers 2

2
from django.core import serializers
data = serializers.serialize("xml", SomeModel.objects.all())

Take a look at the Serialization documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

Assuming the OP wants to dump objects for later retrieval. That's not clear.
0

I don't use version 1.3, so I'm not sure how it works, but could it be that the file is not actually being opened? Could adding myfile.open('w') work? Of course, this may be handled in the File class's init function. Anyway, try giving it a shot and commenting your results.

Update: BTW, I came up with the idea from looking at the docs. Maybe they'll be able to help too. http://docs.djangoproject.com/en/1.3/ref/files/file/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.