@@ -0,0 +1,1735 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0Afrom django.db.models import Count%0A%0A%0Adef set_correct_status(apps, schema_editor):%0A    %22%22%22%0A    Some deals had incorrect status of new business.%0A%0A    This migration tries to fix that for two cases:%0A     - When an account only has one deal.%0A     - When an account has no deal with 'new business' status at all.%0A    %22%22%22%0A    deal_cls = apps.get_model('deals', 'Deal')%0A%0A    # All accounts with one deal -%3E set deal to 'new business'.%0A    account_id_list = deal_cls.objects.values('account').annotate(ac_count=Count('account')).filter(ac_count=1).values_list('account_id', flat=True)%0A    deal_cls.objects.filter(account_id__in=account_id_list).update(new_business=True)%0A%0A    # All accounts with multiple deals, but none 'new business' -%3E set first deal to 'new business'.%0A    account_id_list = deal_cls.objects.values('account').annotate(ac_count=Count('account')).exclude(ac_count=1).values_list('account_id', flat=True)%0A    for account_id in account_id_list:%0A        # Fetch list with deals and check if any of them is new business.%0A        if not deal_cls.objects.filter(account_id=account_id, new_business=True).exists():%0A            # deal with status new business doesn't exist, so set first deal to 'new business'.%0A            deal = deal_cls.objects.filter(account_id=account_id).order_by('created').first()%0A            deal.new_business = True%0A            deal.save()%0A%0A%0Adef backwards_noop(apps, schema_editor):%0A    pass%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A    dependencies = %5B%0A        ('deals', '0007_auto_20150902_1543'),%0A    %5D%0A%0A    operations = %5B%0A        migrations.RunPython(set_correct_status, backwards_noop),%0A    %5D%0A

Migrate certain deals to set status new business