from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.db import transaction
class Command(BaseCommand):
help = 'Import CSV data into the database'
def add_arguments(self, parser):
parser.add_argument('csvfile', type=str, help='The CSV file to import')
parser.add_argument('model_name', type=str, help='The model to import the data into')
@transaction.atomic
def handle(self, *args, **options):
csvfile = options['csvfile']
model_name = options['model_name']
try:
# 尝试导入CSV文件
call_command('import_from_csv', csvfile, model_name)
self.stdout.write(self.style.SUCCESS('Imported %s successfully.' % csvfile))
except Exception as e:
# 如果导入失败,则回滚事务
self.stdout.write(self.style.ERROR('Failed to import %s: %s' % (csvfile, e)))
transaction.rollback()
这个示例代码展示了如何在Django中创建一个命令行工具来导入CSV文件到数据库。它使用了add_arguments
来定义命令行参数,并通过handle
方法处理导入操作。如果导入失败,它会使用transaction.rollback
来确保数据库回滚,保持数据一致性。