-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1732 from mitodl/add-migration-to-delete-invalid-…
…redemptions add migration to delete duplicate discount redemption
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
ecommerce/migrations/0035_delete_duplicate_discountredemption.py
This file contains 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
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 | ||
), | ||
] |