27 lines
1.1 KiB
Python

from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import AbsencePeriod
from calendars.models import Event, EventParticipation
@receiver(post_save, sender=AbsencePeriod)
def handle_absence_period(sender, instance, **kwargs):
user = instance.user
events_in_period = Event.objects.filter(
team=user.team,
start_time__date__gte=instance.start_date,
start_time__date__lte=instance.end_date
)
# Get existing participations for the user and events in the period
existing_participations = EventParticipation.objects.filter(user=user, event__in=events_in_period).values_list('event_id', flat=True)
# Bulk update existing participations
EventParticipation.objects.filter(user=user, event__in=events_in_period).update(status='rejected')
# Bulk create new participations
new_participations = [
EventParticipation(user=user, event=event, status='rejected')
for event in events_in_period if event.id not in existing_participations
]
EventParticipation.objects.bulk_create(new_participations)