Last active
August 29, 2015 14:14
-
-
Save igniteflow/2c4b033cc70cf25b8e84 to your computer and use it in GitHub Desktop.
Django: Set all foreign keys to None to prevent cascade deletions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.db.models import get_models, get_app | |
| MY_APPS = ('foo', 'bar') | |
| # get all the models | |
| models = [] | |
| for app in MY_APPS: | |
| try: | |
| models += get_models(app_mod=get_app(app)) | |
| except ImproperlyConfigured: | |
| # app is missing a models.py | |
| pass | |
| # set all foreign keys to None to prevent cascade deletions | |
| for model in models: | |
| app_model = '{}.{}'.format(model._meta.app_label, model._meta.object_name) | |
| fk_field_names = [ | |
| field.name | |
| for field in model._meta.fields | |
| if isinstance(field, ForeignKey) | |
| ] | |
| for fk_field_name in fk_field_names: | |
| model.objects.all().update(**{fk_field_name: None}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment