mirror of
https://github.com/ae-utbm/sith.git
synced 2024-11-26 02:54:20 +00:00
53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
|
# Generated by Django 4.2.16 on 2024-11-15 12:34
|
||
|
from __future__ import annotations
|
||
|
|
||
|
from operator import attrgetter
|
||
|
from typing import TYPE_CHECKING
|
||
|
|
||
|
import django.db.models.deletion
|
||
|
from django.db import migrations, models
|
||
|
from django.db.models import Count
|
||
|
|
||
|
if TYPE_CHECKING:
|
||
|
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
|
||
|
from django.db.migrations.state import StateApps
|
||
|
|
||
|
|
||
|
def delete_duplicates(apps: StateApps, schema_editor: DatabaseSchemaEditor):
|
||
|
"""Delete cards of users with more than one student cards.
|
||
|
|
||
|
For all users who have more than one registered student card, all
|
||
|
the cards except the last one are deleted.
|
||
|
"""
|
||
|
Customer = apps.get_model("counter", "Customer")
|
||
|
StudentCard = apps.get_model("counter", "StudentCard")
|
||
|
customers = (
|
||
|
Customer.objects.annotate(nb_cards=Count("student_cards"))
|
||
|
.filter(nb_cards__gt=1)
|
||
|
.prefetch_related("student_cards")
|
||
|
)
|
||
|
to_delete = [
|
||
|
card.id
|
||
|
for customer in customers
|
||
|
for card in sorted(customer.student_cards.all(), key=attrgetter("id"))[:-1]
|
||
|
]
|
||
|
StudentCard.objects.filter(id__in=to_delete).delete()
|
||
|
|
||
|
|
||
|
class Migration(migrations.Migration):
|
||
|
dependencies = [("counter", "0024_accountdump_accountdump_unique_ongoing_dump")]
|
||
|
|
||
|
operations = [
|
||
|
migrations.RunPython(delete_duplicates, migrations.RunPython.noop),
|
||
|
migrations.AlterField(
|
||
|
model_name="studentcard",
|
||
|
name="customer",
|
||
|
field=models.OneToOneField(
|
||
|
on_delete=django.db.models.deletion.CASCADE,
|
||
|
related_name="student_card",
|
||
|
to="counter.customer",
|
||
|
verbose_name="student card",
|
||
|
),
|
||
|
),
|
||
|
]
|