Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从视图调用时出错:您可以';直到';结束时才执行查询;原子';块_Python_Django_Django Rest Framework - Fatal编程技术网

Python 从视图调用时出错:您可以';直到';结束时才执行查询;原子';块

Python 从视图调用时出错:您可以';直到';结束时才执行查询;原子';块,python,django,django-rest-framework,Python,Django,Django Rest Framework,我正在尝试测试一个导入csv文件并创建Product对象的视图。问题是它返回以下错误: line 447, in validate_no_broken_transaction raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries un

我正在尝试测试一个导入
csv
文件并创建
Product
对象的视图。问题是它返回以下错误:

line 447, in validate_no_broken_transaction
    raise TransactionManagementError(
django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
该错误是由此行引起的:

 Supplier.objects.get_or_create(name__iexact=supplier__name, defaults={'name': supplier__name})[
方法如下:

@classmethod
def import_csv(cls, filepath: str, created_by: User, delete_file=True) -> int:
    """imports products
    SKU already exists ? skip product : add product """
    from products.models import Product
    from products.models import Supplier
    products_count = 0
    EXCLUDED_ATTRS = ['id', 'supplier']

    with open(filepath) as f:
        reader = csv.DictReader(f)

        for row in reader:
            if not all([row.get(field, None) is not None for field in ['sku', 'supplier__name']]):
                continue

            product = Product()
            product.created_by = created_by

            for attr, val in row.items():
                if hasattr(product, attr) and attr not in EXCLUDED_ATTRS:
                    if attr == 'title':
                        setattr(product, attr, val[:99])
                    else:
                        setattr(product, attr, val)

            supplier__name = row['supplier__name']
            if supplier__name:
                supplier = \
                    Supplier.objects.get_or_create(name__iexact=supplier__name, defaults={'name': supplier__name})[
                        0]
                product.supplier = supplier

            try:
                product.save()
            except IntegrityError:
                pass  # todo what?
            else:
                products_count += 1
        if delete_file:
            os.remove(filepath)
    return products_count
这是一个视图操作:

@action(methods=['post'], detail=False)
def import_csv(self, request, pk=None) -> Response:
    csv_file = request.FILES['file']
    csv_import_files_dir = os.path.join('/tmp/project_imports/')
    csv_file_path = os.path.join(csv_import_files_dir, str(uuid.uuid4()))
    os.makedirs(csv_import_files_dir, exist_ok=True)
    with open(csv_file_path, 'wb') as f:
        f.write(csv_file.read())
    count = product_services.imports.ImportService.import_csv(csv_file_path, request.user)
    return Response({'imported': count})

您知道问题出在哪里吗?

您正在捕获并忽略数据库错误(
除了IntegrityError
)。是否引发异常,然后在出现其他错误之前将其忽略?是否检查了此项?