django: Dump model instances to fixtures

Fixtures are handy when setting up a new copy of your site, but writing them by hand is an absolute pain!

Luckily, the folks at django have saved us yet again.

This little command allows us to select exactly which objects to export, but also how to format it.

from django.core import serializers
from yourapp.models import YourModel

data = serializers.serialize("json", YourModel.objects.all(), indent = 4)

file = open("initial_data.json", 'w')
file.write(data)
file.close()

This will run through and serialise the objects you pass. Just write "data" into the JSON file of your choice!

*update 20/01/2011* Added 3 lines to write the data to a file

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog