Search code examples
djangodjango-rest-frameworkdjango-filterserialization

How to filter relationships based on their fields in response using Django REST Framework


I have three models: House, Resident, Car. Each House has many Residents (One to Many). Each Resident has 0 or 1 cars (One to One). For my frontend, I want to display all the residents of a house that have a car. Django Rest Framework suggests using Filtering, but this only works at the top level. For example, in my HouseDetailView(generics.RetrieveAPIView), I can only modify the queryset of the House model itself. I want to be able to modify the queryset of the Resident (resident_queryset.exclude(car=None)).

class HouseDetailView(generics.RetrieveAPIView):
  queryset = House.objects.all()
  serializer_class = HouseSerializer

Can/Should I do this all in one request? Are query parameters my only way of filtering?


Solution

  • # If you want to display all the residents of a house that have a car, then you should query the car model
    
    
    class CarDetailView(generics.RetrieveAPIView):
        queryset = Car.objects.all()
        serializer_class = CarSerializer
    
    
    serializers.py
    
    class CarSerializer(serializers.ModelSerializer):
    
        # get the resident details (name)
        resident_name = serializers.SerializerMethodField('get_resident_name')
    
        def get_resident_name(self, obj):
            return obj.resident.name
    
    
        class Meta:
            model = Car
            fields = ("name", "resident_name")