12 Django Affairs

First, the transaction

The definition of the transaction: a plurality of operating sql statement into atomic operation, either while successful, a failure which is rolled back to the original state, to ensure the integrity and consistency of the data (for the NoSQL database transaction is supported portion)

Detailed look at the concept of transaction: Interpretation Services

Second, the example

How to open a transaction in Django

# 事务
    # 买一本 跟老男孩学Linux 书
    # 在数据库层面要做的事儿
    # 1. 创建一条订单数据
    # 2. 去产品表 将卖出数+1, 库存数-1
    from django.db.models import F
    from django.db import transaction
    # 开启事务处理
    try:
        with transaction.atomic():
            # 在with代码块中写的代码属于同一个事务
            # 创建一条订单数据
            models.Order.objects.create(num="110110111", product_id=1, count=1)
            # 能执行成功
            models.Product.objects.filter(id=1).update(kucun=F("kucun")-1, maichu=F("maichu")+1)
    except Exception as e:
        print(e)

Guess you like

Origin www.cnblogs.com/xichenHome/p/11748018.html