Reputation: 79
I would like to save a Django model into a json file into a specific directory. How can I do that? My code is below in views.py.
def JSON(request):
with open(r'C:\Users\Savas\Desktop\DOCUMENTS\file.json', "w") as out:
mast_point = serializers.serialize("json", Poi.objects.all())
out.write(mast_point)
Upvotes: 3
Views: 7557
Reputation: 576
As of version 1.1 and greater, the Django dumpdata management command allows you to dump data from individual tables:
./manage.py dumpdata myapp2.my_model > fixtures/file_name.json
Upvotes: 3
Reputation: 165
Good morning!
did you look at the documentation for this? :)
Additionally i would suggest that you indent you code like the following:
from django.core import serializers
from .models import yourmodel
from django.http import HttpResponse
def example(request):
objects = yourmodel.objects.all()
with open(r'...your path...\file.json', "w") as out:
mast_point = serializers.serialize("json", objects)
out.write(mast_point)
template = loader.get_template('some_template.html')
context = {'object': objects}
return HttpResponse(template.render(context, request))
I just tried this code snippet and it worked in my sample django application, of course you have to adapt this snippet a little bit :)
Upvotes: 3