From 11a471ae01b1ad80f090d952a744679aac6d5d15 Mon Sep 17 00:00:00 2001 From: Diederik van der Boor Date: Mon, 9 Jan 2017 14:38:51 +0100 Subject: [PATCH] Add reset_polymorphic_ctype() function to assist with migration to polymorphic --- polymorphic/utils.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 polymorphic/utils.py diff --git a/polymorphic/utils.py b/polymorphic/utils.py new file mode 100644 index 0000000..23d7a01 --- /dev/null +++ b/polymorphic/utils.py @@ -0,0 +1,22 @@ +from django.contrib.contenttypes.models import ContentType + + +def reset_polymorphic_ctype(*models, **filters): + """ + Set the polymorphic content-type ID field to the proper model + Sort the ``*models`` from base class to descending class, + to make sure the content types are properly assigned. + + Add ``preserve_existing=True`` to skip models which already + have a polymorphic content type. + """ + preserve_existing = filters.pop('preserve_existing', False) + for new_model in models: + new_ct = ContentType.objects.get_for_model(new_model) + + qs = new_model.objects.all() + if preserve_existing: + qs = qs.filter(polymorphic_ctype__isnull=True) + if filters: + qs = qs.filter(**filters) + qs.update(polymorphic_ctype=new_ct)