Committing auth_permission table after renaming model in Django

From time to time you need to rename the model in Django (or in one recent case that I came across, split one model into two, with new / different names). Yes, proper planning helps to avoid this situation, but sometimes reality intervenes.

After renaming the corresponding tables in db and fixing the affected code, one problem remains: Any permissions granted to users or groups to work with these models still refer to the old model names. Is there any automated or semi-automated way to fix this, or is it just a matter of manual surgery db? (In development, you can reset the auth_permissions and syncdb tables to recreate it, but production is not so simple).

+6
django django-models
source share
4 answers

Here's a snippet that populates missing content types and permissions. I wonder if it can be extended, at least to run some donkeys to clean auth_permissions.

+2
source share

If you used south schema migration to rename the table, the next line in the transition redirection is done automatically:

db.send_create_signal('appname', ['modelname']) 
+2
source share

I recently had this problem and wrote a function to solve it. If you rename the model / table, you will usually have a mismatch of both the ContentType and Permission tables. Django has built-in helper functions to solve the problem, and you can use them as follows:

 from django.contrib.auth.management import create_permissions from django.contrib.contenttypes.management import update_all_contenttypes from django.db.models import get_apps def update_all_content_types_and_permissions(): for app in get_apps(): create_permissions(app, None, 2) update_all_contenttypes() 
+1
source share

I got halfway through a long answer detailing the attack plan I would take in this situation, but as I wrote, I realized that there might be no way to make the service downtime in this situation.

You can minimize downtime by having, of course, a prepared loaddata script, although you must ensure that the primary keys of auth_perms are in sync.

Also see the short answer: there is no automated way to do this that I know of.

0
source share

All Articles