Skip to content
Advertisement

How To give optional parameter in DRF

Hi Everyone i am created one api, where i will use [city] as first parameter to get result based on city, but i need [id] also as second parameter but [id] is optional, same time we use [id] as second parameter and sometime not, please help me out

for ex-

1-get data based on city

url=127.0.0.1:8000/api/car/city

2-get data based on city and id

url= 127.0.0.1:8000/api/car/city/id

serializers.py

class CarNumberSerializer(serializers.ModelSerializer):
    model=CarModelNameSerializer()
    company=CarCompanySerializer()
    class Meta:
        model = Car
        fields = ['id','car_number','model','company']

views.py

class CarNumberViewset(viewsets.ModelViewSet):
    queryset=Car.objects.all()
    serializer_class= CarNumberSerializer

    def retrieve(self, request, *args, **kwargs):
        params= kwargs
        params_list=params['pk']
        car=Car.objects.filter(city=params_list)
        serializer=CarNumberSerializer(car,many=True)
        return Response(serializer.data)

urls.py

routers.register(r'gms/car_list',CarNumberViewset)

Advertisement

Answer

def retreive(...) is for getting a single Car object by primary-key. For example gms/car_list/1 will return the Car object with id 1.

Right now you have replaced the car’s id with a city id.

I would use list method instead with django-filter.

  1. Install django-filter (check docs).
  2. Replace with:
class CarNumberViewset(viewsets.ModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarNumberSerializer
    filterset_fields = ('city', 'id')
    
    # No need to overwrite list() or retrieve() here. DRF handles everything.
  1. Now you can send a request to /gms/car_list?city=4&id=1 to filter by id and city.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement