进行迁移时Django中的TransactionManagementError
Posted
技术标签:
【中文标题】进行迁移时Django中的TransactionManagementError【英文标题】:TransactionManagementError in Django when make migrate 【发布时间】:2022-01-09 12:14:51 【问题描述】:我是编程新手,在 Django 3.2.9 中进行迁移时遇到问题。
这是我的代码,models.py
from django.db import models
from django.db.models.deletion import CASCADE, PROTECT
# Create your models here.
class Promotion(models.Model):
description = models.CharField(max_length=255)
discount = models.FloatField()
class Collection(models.Model):
title = models.CharField(max_length=255)
class Product(models.Model):
slug = models.SlugField()
title = models.CharField(max_length=255)
description = models.TextField()
unit_price = models.DecimalField(max_digits=6, decimal_places=2)
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(Collection, on_delete=models.PROTECT)
promotions = models.ManyToManyField(Promotion)
class Customer(models.Model):
MEMBERSHIP_BRONZE = 'B'
MEMBERSHIP_SILVER = 'S'
MEMBERSHIP_GOLD = 'G'
MEMBERSHIP_CHOICES = [
(MEMBERSHIP_BRONZE, 'Bronze'),
(MEMBERSHIP_SILVER, 'Silver'),
(MEMBERSHIP_GOLD, 'Gold')
]
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=255)
birth_date = models.DateField(null=True)
membership = models.CharField(
max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE)
class Order(models.Model):
STATUS_Pending = 'P'
STATUS_Complete = 'C'
STATUS_Failed = 'F'
STATUS_CHOICES = [
(STATUS_Pending, 'Pending'),
(STATUS_Complete, 'Complete'),
(STATUS_Failed, 'Failed')
]
placed_at = models.DateTimeField(auto_now_date=True)
payment_status = models.CharField(
max_length=1, choices=STATUS_CHOICES, default=STATUS_Pending)
customer = models.ForeignKey(Customer, on_delete=PROTECT)
class Address(models.Model):
street = models.CharField(max_length=255)
city = models.CharField(max_length=255)
customer = models.OneToOneField(
Customer, on_delete=models.CASCADE, primary_key=True)
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=PROTECT)
product = models.ForeignKey(Product, on_delete=PROTECT)
quantiy = models.PositiveSmallIntegerField()
unit_price = models.DecimalField(max_digits=5, decimal_places=2)
class Cart(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=CASCADE)
product = models.ForeignKey(Product, on_delete=CASCADE)
quantity = models.PositiveSmallIntegerField()
我成功运行:python manage.py makemigrations 但是当我运行:python manage.py migrate 时, 我遇到了一个问题
Operations to perform:
Apply all migrations: admin, auth, contenttypes, likes, store, tags
Running migrations:
Applying contenttypes.0001_initial...Traceback (most recent call last):
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: django_migrations.applied
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\migrations\executor.py", line 229, in apply_migration
self.record_migration(migration)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\migrations\executor.py", line 244, in record_migration
self.recorder.record_applied(migration.app_label, migration.name)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\migrations\recorder.py", line 87, in record_applied
self.migration_qs.create(app=app, name=name)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
cursor.execute(sql, params)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: django_migrations.applied
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\FR\Python_VScode\django_app\manage.py", line 22, in <module>
main()
File "C:\Users\FR\Python_VScode\django_app\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\migrations\executor.py", line 230, in apply_migration
migration_recorded = True
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\sqlite3\schema.py", line 35, in __exit__
self.connection.check_constraints()
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in check_constraints
violations = cursor.execute('PRAGMA foreign_key_check').fetchall()
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\utils.py", line 78, in _execute
self.db.validate_no_broken_transaction()
File "C:\Users\FR\.virtualenvs\django_app-u_SNPGdA\lib\site-packages\django\db\backends\base\base.py", line 454, 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.
((django_app) ) PS C:\Users\FR\Python_VScode\django_app>
谁能给我解释一下?我是编程新手,4个多月。我正在使用 Django 3.2.9。
非常感谢。
【问题讨论】:
【参考方案1】:在您的 migrations.py 文件夹中,您可以尝试手动删除除 0001_initial.py 文件之外的所有文件。然后运行,
python manage.py makemigrations <appname>
python manage.py migrate <appname>
这可能会解决您的问题。
【讨论】:
嘿,SANGEETH SUBRAMONIAM,我尝试按照您的步骤操作,但运行时仍然卡住:python manage.py migrate , 尝试为除主要 hey 之外的所有属性设置 null=True 然后进行迁移,然后再迁移 嘿,还是不行。当我将除主键之外的属性设置为 True 并运行 make 迁移时,但是当我运行:迁移时,它显示错误:` django.db.utils.OperationalError: table "store_cart" already exists ` 查看这里***.com/questions/25924858/…以上是关于进行迁移时Django中的TransactionManagementError的主要内容,如果未能解决你的问题,请参考以下文章