|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import unicode_literals |
| 3 | + |
| 4 | +from django.apps import apps as global_apps |
| 5 | +from django.contrib.contenttypes.management import update_contenttypes |
| 6 | +from django.db import models, migrations |
| 7 | +from django.utils.timezone import now |
| 8 | + |
| 9 | +MARKER = '.. Migrated from django_comments_xtd.Comment model.\n\n' |
| 10 | + |
| 11 | +comments_app_name = 'django_comments_xtd' |
| 12 | +content_type = 'job' |
| 13 | + |
| 14 | + |
| 15 | +def migrate_old_content(apps, schema_editor): |
| 16 | + try: |
| 17 | + Comment = apps.get_model(comments_app_name, 'XtdComment') |
| 18 | + except LookupError: |
| 19 | + # django_comments_xtd isn't installed. |
| 20 | + return |
| 21 | + update_contenttypes(apps.app_configs['contenttypes']) |
| 22 | + JobReviewComment = apps.get_model('jobs', 'JobReviewComment') |
| 23 | + Job = apps.get_model('jobs', 'Job') |
| 24 | + ContentType = apps.get_model('contenttypes', 'ContentType') |
| 25 | + db_alias = schema_editor.connection.alias |
| 26 | + try: |
| 27 | + job_contenttype = ContentType.objects.using(db_alias).get(name=content_type) |
| 28 | + except ContentType.DoesNotExist: |
| 29 | + return |
| 30 | + old_comments = Comment.objects.using(db_alias).filter( |
| 31 | + content_type=job_contenttype.pk, is_public=True, is_removed=False, |
| 32 | + ) |
| 33 | + found_jobs = {} |
| 34 | + comments = [] |
| 35 | + for comment in old_comments: |
| 36 | + try: |
| 37 | + job = found_jobs[comment.object_pk] |
| 38 | + except KeyError: |
| 39 | + try: |
| 40 | + job = Job.objects.using(db_alias).get(pk=comment.object_pk) |
| 41 | + found_jobs[comment.object_pk] = job |
| 42 | + except Job.DoesNotExist: |
| 43 | + continue |
| 44 | + review_comment = JobReviewComment( |
| 45 | + job=job, |
| 46 | + comment=MARKER + comment.comment, |
| 47 | + creator=comment.user, |
| 48 | + created=comment.submit_date, |
| 49 | + updated=now(), |
| 50 | + ) |
| 51 | + comments.append(review_comment) |
| 52 | + JobReviewComment.objects.using(db_alias).bulk_create(comments) |
| 53 | + |
| 54 | + |
| 55 | +def delete_migrated_content(apps, schema_editor): |
| 56 | + JobReviewComment = apps.get_model('jobs', 'JobReviewComment') |
| 57 | + db_alias = schema_editor.connection.alias |
| 58 | + JobReviewComment.objects.using(db_alias).filter(comment__startswith=MARKER).delete() |
| 59 | + |
| 60 | + |
| 61 | +class Migration(migrations.Migration): |
| 62 | + |
| 63 | + dependencies = [ |
| 64 | + ('contenttypes', '0001_initial'), |
| 65 | + ('jobs', '0011_jobreviewcomment'), |
| 66 | + ] |
| 67 | + if global_apps.is_installed(comments_app_name): |
| 68 | + dependencies.append((comments_app_name, '0001_initial')) |
| 69 | + |
| 70 | + operations = [ |
| 71 | + migrations.RunPython(migrate_old_content, delete_migrated_content), |
| 72 | + ] |
0 commit comments