Django 数据库迁移:删除不能正常工作
Django database migration: delete doesn't work properly
我在 Ubuntu 18.04 中使用 Django 2.2 和 psql 10.12。在迁移时,我试图删除数据库 table auth_permission.
中的一些行
from django.db import migrations
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
def remove_rows_at_migrate(apps, schema_editor):
try:
permission_model = apps.get_model("auth", "Permission")
db_alias = schema_editor.connection.alias
permissions = permission_model.objects.using(db_alias).filter(Q(name='Can do X') |
Q(name='Can do Y'))
for perm in permissions:
print("deleting: {}".format(perm.name))
perm.delete()
except (ObjectDoesNotExist, ValueError):
pass
class Migration(migrations.Migration):
dependencies = [
('abc', 'xxx'),
]
operations = [
migrations.RunPython(remove_rows_at_migrate)
]
当我迁移时,迁移被应用并且结果是 [OK] 但是当我检查 table auth_persmission “可以做 X”和“可以做 Y”仍然在 table 使用新的“id”。
我可以从 manage.py shell_plus 中的相同 table 中删除行,而不会出现以下问题:
>>> permissions = Permission.objects.filter(Q(name='Can do X') |Q(name='Can do Y'))
>>> permissions.delete()
什么会导致这种行为?
因为 permissions
是使用 post_migrate
信号而不是迁移创建的,请参阅 discussions here
我在 Ubuntu 18.04 中使用 Django 2.2 和 psql 10.12。在迁移时,我试图删除数据库 table auth_permission.
中的一些行from django.db import migrations
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
def remove_rows_at_migrate(apps, schema_editor):
try:
permission_model = apps.get_model("auth", "Permission")
db_alias = schema_editor.connection.alias
permissions = permission_model.objects.using(db_alias).filter(Q(name='Can do X') |
Q(name='Can do Y'))
for perm in permissions:
print("deleting: {}".format(perm.name))
perm.delete()
except (ObjectDoesNotExist, ValueError):
pass
class Migration(migrations.Migration):
dependencies = [
('abc', 'xxx'),
]
operations = [
migrations.RunPython(remove_rows_at_migrate)
]
当我迁移时,迁移被应用并且结果是 [OK] 但是当我检查 table auth_persmission “可以做 X”和“可以做 Y”仍然在 table 使用新的“id”。
我可以从 manage.py shell_plus 中的相同 table 中删除行,而不会出现以下问题:
>>> permissions = Permission.objects.filter(Q(name='Can do X') |Q(name='Can do Y'))
>>> permissions.delete()
什么会导致这种行为?
因为 permissions
是使用 post_migrate
信号而不是迁移创建的,请参阅 discussions here