I am using Django 2.2 and psql 10.12 in Ubuntu 18.04. At migration I am trying to remove some rows in database 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)
]
when I migrate, migration is applied and result is [OK] but when I check table auth_persmission "Can do X" and "Can do Y" is still in the table with a new "id".
I can delete rows from same table in manage.py shell_plus without any problems with the following:
>>> permissions = Permission.objects.filter(Q(name='Can do X') |Q(name='Can do Y'))
>>> permissions.delete()
What could cause this behavior?
Because permissions
are created using post_migrate
signal rather than migrations, see discussions here