47 lines
1.9 KiB
Python
47 lines
1.9 KiB
Python
# Generated by Django 1.11.18 on 2020-10-21 11:56
|
|
|
|
from django.db import migrations
|
|
from django.db.models import Count, F
|
|
|
|
|
|
def remove_broken_exceptions(apps, schema_editor):
|
|
TimePeriodException = apps.get_model('agendas', 'TimePeriodException')
|
|
qs = TimePeriodException.objects.filter(source__settings_slug__isnull=False)
|
|
# an exception is broken if its desk in not the same at the desk of its source
|
|
qs.exclude(source__desk=F('desk')).delete()
|
|
|
|
|
|
def remove_duplicate_sources(apps, schema_editor):
|
|
Desk = apps.get_model('agendas', 'Desk')
|
|
for desk in Desk.objects.all():
|
|
duplicate_source_slugs = (
|
|
desk.timeperiodexceptionsource_set.values('settings_slug')
|
|
.annotate(count=Count('settings_slug'))
|
|
.order_by()
|
|
.filter(count__gt=1)
|
|
)
|
|
if not duplicate_source_slugs:
|
|
continue
|
|
for source in duplicate_source_slugs:
|
|
settings_slug = source['settings_slug']
|
|
duplicate_sources = desk.timeperiodexceptionsource_set.filter(settings_slug=settings_slug)
|
|
# remove duplicates, keeping the one that has related time period exceptions, if any
|
|
source_to_keep = duplicate_sources.filter(timeperiodexception__isnull=False).first()
|
|
if not source_to_keep:
|
|
# if no source had exceptions, try to keep one that is flagged as disabled
|
|
source_to_keep = duplicate_sources.filter(enabled=False).first()
|
|
if not source_to_keep:
|
|
source_to_keep = duplicate_sources.first()
|
|
duplicate_sources.exclude(pk=source_to_keep.pk).delete()
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
dependencies = [
|
|
('agendas', '0065_unavailability_calendar'),
|
|
]
|
|
|
|
operations = [
|
|
migrations.RunPython(remove_broken_exceptions, migrations.RunPython.noop),
|
|
migrations.RunPython(remove_duplicate_sources, migrations.RunPython.noop),
|
|
]
|