Skip to content

Instantly share code, notes, and snippets.

@godd0t
Created July 19, 2022 17:32
Show Gist options
  • Save godd0t/0c46400513e7d2b2579c9146758572ef to your computer and use it in GitHub Desktop.
Save godd0t/0c46400513e7d2b2579c9146758572ef to your computer and use it in GitHub Desktop.
import tempfile
from django.contrib import admin
from django.core import serializers
from django.http import HttpResponse
from example_app.models import *
@admin.action(description="Export Model")
def export_model(modeladmin, request, queryset):
# Initialize temporary file so we can write on it during the iteration
model_file = tempfile.TemporaryFile()
with model_file as tmp_file:
# Apply serialization
serialized_objects = serializers.serialize(
"json", queryset
)
# Write in file
tmp_file.write(serialized_objects.encode("utf-8"))
# Go to the beggining of the file
tmp_file.seek(0)
response = HttpResponse(tmp_file.read(), content_type="application/json")
response["Content-Disposition"] = "attachment; filename=model.json"
return response
class PersonAdmin(admin.ModelAdmin):
actions = [export_model]
admin.site.register(Person, PersonAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment