在Django中下载完整数据库的问题

发布于 2025-01-26 01:45:13 字数 3519 浏览 2 评论 0原文

首先,我使用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 )

First I used export_import to download the database but I only downloaded a single table at a time but I need to export the entire database to a file then import it back. Now I'm trying to fix it with another way I just saw using resources

If you could help me to change it to a view instead of a function I would be grateful.

Note: Thanks for the help.

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        

This is the html file to call the function to download the database
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 )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海少女心 2025-02-02 01:45:13

尝试将其粘贴在您的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

编辑:

您可能想使用这些args dumpdata

call_command('dumpdata', natural_foreign=True, natural_primary=True, exclude=['contenttypes', 'auth'])

Try sticking this in your 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

Might also be worth reading up on dumpdata and call_command

Edit:

You probably want to dumpdata with these args:

call_command('dumpdata', natural_foreign=True, natural_primary=True, exclude=['contenttypes', 'auth'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文