models:
class Publisher(models.Model):
name = models.CharField(max_length=32, verbose_name="名称",unique=True)
事务:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE","about_orm.settings")
import django
django.setup()
from app01 import models
from django.db import transaction
#写法一:
# try:
# with transaction.atomic():
# #一系列的ORM操作:
# models.Publisher.objects.create(name="xxx")
# models.Publisher.objects.create(name="xxx")
# except Exception as e:
# print(e)
# print("xxx")
#写法二:
with transaction.atomic():
try:
models.Publisher.objects.create(name="xxx")
models.Publisher.objects.create(name="xxx")
except Exception as e:
print(e)
print("xxx")