I am building an API using Django rest framework. I currently have an endpoint /api/v1/device-groups/ which returns all device group objects like this:

        "device_group_name": "Default",
        "group_uuid": "3812a299-3ab9-4c00-a711-d166fb01075e",
        "color": "4286f4",
        "is_default": true,
        "customer": {
            "customer_name": "Testcustomer",
            "customer_uuid": "179fe73d-ec67-45ac-8dac-e2456ccd9b48"

Using the customer_uuid in the URL shows the device groups related to that customer

/api/v1/device-groups/179fe73d-ec67-45ac-8dac-e2456ccd9b48 returns data of the device groups attached to the specified customer_uuid

The problem I am facing is that whenever there are multiple device groups related to a customer_uuid it results in a MultipleObjectsReturned error. I want to list all the device groups that are related to the specified customer_uuid.

My serializers.py:

class CustomerSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Customer
        fields = ('customer_name', 'customer_uuid')

class DeviceGroupSerializer(serializers.HyperlinkedModelSerializer):
    customer = CustomerSerializer(many=False, read_only=True, source='customer_uuid')

    class Meta:
        model = DeviceGroup
        fields = ('device_group_name', 'group_uuid', 'color', 'is_default', 'customer')

My views.py:

class DeviceGroupViewSet(viewsets.ModelViewSet):
    serializer_class = DeviceGroupSerializer
    lookup_field = 'customer_uuid'

    def get_queryset(self):
        queryset = DeviceGroup.objects.all()
        customer_uuid = self.request.query_params.get('customer_uuid', None)
        if customer_uuid is not None:
            queryset = queryset.filter(customer_uuid=customer_uuid)
        return queryset

What do I need to change so all device groups related to a customer_uuid are returned?

0 Answers