Проблема с загрузкой полной базы данных в Django
Сначала я использовал export_import для загрузки базы данных, но я загрузил только одну таблицу за раз, но мне нужно экспортировать всю базу данных в файл, а затем импортировать ее обратно. Теперь я пытаюсь исправить это с помощью другого способа, который я только что увидел, используя ресурсы
Если бы вы могли помочь мне изменить его на представление вместо функции, я был бы благодарен.
Примечание: Спасибо за помощь.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .resources import CommentResource, CategoryResource
# Create your views here.
def export_data(request):
if request.method == 'POST':
# Get selected option from form
file_format = request.POST['file-format']
comment_resource = CommentResource()
dataset = comment_resource.export()
print(type(CommentResource()))
print(type(CategoryResource()))
if file_format == 'CSV':
response = HttpResponse(dataset.csv, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="exported_data.csv"'
return response
elif file_format == 'JSON':
response = HttpResponse(dataset.json, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename="exported_data.json"'
return response
elif file_format == 'XLS (Excel)':
response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="exported_data.xls"'
return response
return render(request, 'export_import_data_page.html')
resources.py
from import_export import resources
from label.models import Comment, Category
class CommentResource(resources.ModelResource):
class Meta:
model = Comment
class CategoryResource(resources.ModelResource):
class Meta:
model = Category
Это html-файл для вызова функции загрузки базы данных export_import_data_page.html
<!DOCTYPE html>
<html>
<head>
<title>Título de mi página web</title>
</head>
<body>
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title">Export Comments</h3>
</div>
<div class="card-body">
<form role="form" method="POST" action="{% url 'label:export_data' %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label>Choose Format Type</label>
<select class="custom-select" name="file-format">
<option selected>Choose format...</option>
<option>CSV</option>
<option>JSON</option>
<option>XLS (Excel)</option>
</select>
</div> <br><br><br>
<button type="submit" class="btn btn-info btn-block">Export</button>
</form>
</div>
</div>
</body>
</html>
models.py
from django.db import models
class Category(models.Model):
title = models.CharField(max_length = 500, unique=True)
def __str__(self):
return "{0}".format(self.title)
class Comment(models.Model):
description = models.TextField()
category = models.ForeignKey(Category, on_delete= models.CASCADE )
Попробуйте засунуть это в свой views.py
import sys
from django.core.management import call_command
sysout = sys.stdout
sys.stdout = open('filename.json', 'w')
call_command('dumpdata')
sys.stdout = sysout
Возможно, также стоит прочитать о dumpdata и call_command
Редактирование:
Вы, вероятно, захотите dumpdata с этими аргументами:
call_command('dumpdata', natural_foreign=True, natural_primary=True, exclude=['contenttypes', 'auth'])