Skip to content

Commit

Permalink
Merge pull request #1732 from mitodl/add-migration-to-delete-invalid-…
Browse files Browse the repository at this point in the history
…redemptions

add migration to delete duplicate discount redemption
  • Loading branch information
rachellougee authored Jul 17, 2023
2 parents bde6417 + 3bf6e15 commit 9669d31
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions ecommerce/migrations/0035_delete_duplicate_discountredemption.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Generated by Django 3.2.18 on 2023-07-07 15:13

from django.db import migrations
from django.db.models import Count


def delete_duplicate_discountredemption(apps, schema_editor):
DiscountRedemption = apps.get_model("ecommerce", "DiscountRedemption")

duplicate_ids = (
DiscountRedemption.objects.values("redeemed_order_id")
.annotate(num_orders=Count("redeemed_order_id"))
.filter(num_orders__gt=1)
.values_list("redeemed_order_id", flat=True)
)

# sort duplicate DiscountRedemption so that the same orders group together with the most recent one on top
duplicate_redemptions = (
DiscountRedemption.objects.filter(redeemed_order_id__in=duplicate_ids)
.order_by("redeemed_order_id", "-created_on")
.all()
)

last_seen_order_id = 0
for row in duplicate_redemptions:
if row.redeemed_order_id == last_seen_order_id:
row.delete()
else:
last_seen_order_id = row.redeemed_order_id


class Migration(migrations.Migration):
dependencies = [
("ecommerce", "0034_add_bulk_field_to_discounts"),
]

operations = [
migrations.RunPython(
delete_duplicate_discountredemption, migrations.RunPython.noop
),
]

0 comments on commit 9669d31

Please sign in to comment.