How do I filter in URL a serializer when it's nested in another serializer In Django?

Viewed 94

I'm creating an API that has nested data like in the picture enter image description here Now how to search nested data in URL here's my model

class Robot(models.Model):
    robot = models.CharField(max_length=100)
    short_Description = models.CharField(max_length=200)
    status = models.CharField(max_length=20)
    parameter = models.CharField(max_length=200)
    jenkins_job = models.CharField(max_length=100, default='JenkinsJobName')
    jenkins_token = models.CharField(max_length=100, default='JenkinsToken')
    def __str__(self):
        return self.robot

class assignParameter(models.Model): 
    parameterName = models.CharField(max_length=100, blank=True)
    assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True)

Here's my serializer.py

from .models import Robot,assignParameter
from rest_framework import serializers

class assignParameterSerializer(serializers.ModelSerializer):
    class Meta: 
        model = assignParameter
        fields = ['id', 'parameterName', 'assignRobot']


class RobotSerializer(serializers.ModelSerializer):
    param = assignParameterSerializer(many=True, read_only=True)
    JenkinJobName = jenkinsHistorySerializer(many=True, read_only=True)
    class Meta: 
        model = Robot
        fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job',  'jenkins_token', 'param']

and here's my view for the api

class RobotViewSet(viewsets.ModelViewSet):
    queryset = Robot.objects.all()
    serializer_class = RobotSerializer
    filter_backends = [filters.DjangoFilterBackend]
    filterset_fields = ['robot', 'JenkinJobName__jenkinsBuildNumber']
    authentication_classes = [BasicAuthentication]
    permission_classes = [IsAuthenticated]

in the API URL if I want to search a particular robot then using this URL URL/?robot=robotname I'm able to search that particular robot. But how can I search particular nested data using URL?

using my view I'm getting search filters like thisenter image description here

But that is not performing any Search. how to achieve that search and what is wrong with my code can someone please help me? Actually when i search nested serializer only searched value should be present in list other should to be disappear.

1 Answers

Maybe you will need to overwrite your list method in your view, here it is how actually works, you can add whathever you want to filter or maybe you will need to overwrite your queryset depending on the parameters you want.

Related