且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将csv文件中的数据加载到Django模型中

更新时间:2023-12-02 18:33:40

在视图函数中执行此逻辑不是一个好主意.我不知道您为什么会这样,但是可以触发两次相同的视图功能(例如,将Google Chrome浏览器之类的浏览器粘贴到地址栏中后,往往会在后台预取网址-这可能会导致两个我不知道这是否是问题所在,但可能值得排除.)

Performing this logic in a view function is not a good idea. I don't know exactly why in your case, but it is possible to trigger the same view function twice (e.g., browsers like Google Chrome often prefetch URLs in the background as soon as you paste them into the address bar - this can cause two hits on that view. I don't know whether that is the problem here but it may be worth ruling out).

您应该考虑将此逻辑转移到自定义管理命令中可以确定地调用.像这样:

You should consider moving this logic into a custom management command that you can call deterministically. Something like:

# myapp/management/commands/import_csv.py
from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('csv_file', nargs='+', type=str)

    def handle(self, *args, **options):
        for csv_file in options['csv_file']:
            dataReader = csv.reader(open(csv_file), delimiter=',', quotechar='"')
            for row in dataReader:
                emp = Employee()
                # etc...
                self.stdout.write(
                    'Created employee {} {}'.format(emp.first_name, emp.last_name)
                )

然后您可以通过以下方式调用它:

You would then call this with:

./manage.py import_csv --csvfile "/home/<name>/webapps/<name2>/employees.csv"

这种方法使您可以更好地控制正在发生的事情,并且可以更轻松地调试问题(如果仍有问题的话).

This approach gives you more control over what is going on and will make it easier to debug the issue (if there still is one).