diff --git a/care/facility/api/serializers/asset.py b/care/facility/api/serializers/asset.py index 430e2028c8..2ccdd8fa85 100644 --- a/care/facility/api/serializers/asset.py +++ b/care/facility/api/serializers/asset.py @@ -2,6 +2,7 @@ from django.core.cache import cache from django.db import transaction +from django.db.models import Q from django.shortcuts import get_object_or_404 from django.utils.timezone import now from rest_framework import serializers @@ -100,22 +101,23 @@ class Meta: "duty_staff", ) - def validate(self, attrs): - duty_staff = attrs.get("duty_staff", []) - if not duty_staff: + def validate_duty_staff(self, value): + if not value: raise ValidationError({"duty_staff": "Duty staff cannot be empty"}) - duty_staff_ids = [user.id for user in duty_staff] + duty_staff_ids = [user.id for user in value] facility_id = self.instance.facility.id - users = User.objects.filter(id__in=duty_staff_ids) - for user in users: - if user.home_facility.id != facility_id: - raise ValidationError( - {"duty_staff": "Only Home Facility Doctors and Staffs are allowed"} - ) + count = User.objects.filter( + Q(home_facility__id=facility_id) & Q(id__in=duty_staff_ids) + ).count() - return super().validate(attrs) + if count != len(duty_staff_ids): + raise ValidationError( + {"duty_staff": "Only Home Facility Doctors and Staffs are allowed"} + ) + + return value class AssetBareMinimumSerializer(ModelSerializer):