serializers.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from rest_framework import serializers
  2. from .models import AlertRecipient, ProjectAlert
  3. class AlertRecipientSerializer(serializers.ModelSerializer):
  4. recipientType = serializers.CharField(source="recipient_type")
  5. class Meta:
  6. model = AlertRecipient
  7. fields = ("pk", "recipientType", "url")
  8. class ProjectAlertSerializer(serializers.ModelSerializer):
  9. alertRecipients = AlertRecipientSerializer(
  10. source="alertrecipient_set", many=True, required=False
  11. )
  12. class Meta:
  13. model = ProjectAlert
  14. fields = (
  15. "pk",
  16. "name",
  17. "timespan_minutes",
  18. "quantity",
  19. "uptime",
  20. "alertRecipients",
  21. )
  22. def create(self, validated_data):
  23. alert_recipients = validated_data.pop("alertrecipient_set", [])
  24. instance = super().create(validated_data)
  25. for recipient in alert_recipients:
  26. instance.alertrecipient_set.create(**recipient)
  27. return instance
  28. def update(self, instance, validated_data):
  29. alert_recipients = validated_data.pop("alertrecipient_set", [])
  30. instance = super().update(instance, validated_data)
  31. # Create/Delete recipients as needed
  32. delete_recipient_ids = set(
  33. instance.alertrecipient_set.values_list("id", flat=True)
  34. )
  35. for recipient in alert_recipients:
  36. new_recipient, created = AlertRecipient.objects.get_or_create(
  37. alert=instance, **recipient
  38. )
  39. if not created:
  40. delete_recipient_ids.discard(new_recipient.pk)
  41. if delete_recipient_ids:
  42. instance.alertrecipient_set.filter(pk__in=delete_recipient_ids).delete()
  43. return instance