So I created my "API" using REST framework, now trying to do filtering for it.
That's how my models.py
look like more or less:
class Airline(models.Model):
name = models.TextField()
class Workspace(models.Model):
airline = models.ForeignKey(Airline)
name = models.CharField(max_length=100)
class Passenger(models.Model):
workspace = models.ForeignKey(Workspace)
title = models.CharField(max_length=200)
So I would like to see in my JSON file "all passengers in particular workspace" or "all passengers in particular airline" etc.
Here is my, serializers.py
class AirlineSerializer(serializers.ModelSerializer):
class Meta:
model = Airline
class WorkspaceSerializer(serializers.ModelSerializer):
class Meta:
model = Workspace
class PassengerSerializer(serializers.ModelSerializer):
class Meta:
model = Passenger
And views.py
:
class AirlineList(generics.ListCreateAPIView):
model = Airline
serializer_class = AirlineSerializer
class AirlineDetail(generics.RetrieveUpdateDestroyAPIView):
model = Airline
serializer_class = AirlineSerializer
class WorkspaceList(generics.ListCreateAPIView):
model = Workspace
serializer_class = WorkspaceSerializer
class WorkspaceDetail(generics.RetrieveUpdateDestroyAPIView):
model = Workspace
serializer_class = WorkspaceSerializer
class PassengerList(generics.ListCreateAPIView):
model = Passenger
serializer_class = PassengerSerializer
class PassengerDetail(generics.RetrieveUpdateDestroyAPIView):
model = Passenger
serializer_class = PassengerSerializer
It's my first time using REST framework, I have checked the docs, they helped me with what I've done so far, I would like to use
Filtering against query parameter: http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters
Can't really get it..
So with the @limelights I managed to do what I wanted, here is the code:
You can get the same functionality out of the box just by using django-filter package as stated in the docs http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend
In this case you will have to make filtering using 'workspace=1' or 'workspace__airline=1'
This django app applies filters on the queryset of a view using the incoming query parameters in an clean and elegant way.
Which can be installed with pip as
pip install drf-url-filters
Usage Example
validations.py
views.py