[Django]-How to list all items based on foreign key pk Django Rest Framework

4👍

✅

In that case you probably want to use a ListAPIView (docs) and filter based on the primary key of the Animal, so:

class MyAnimalSex(generics.ListAPIView):
    queryset = AnimalSex.objects.all()
    serializer_class = AnimalSexSerializer

    def get_queryset(self):
        return super().get_queryset().filter(
            animal_id=self.kwargs['pk']
        )

0👍

You can use lookup_field:

class MyAnimalSex(generics.RetrieveAPIView):
    queryset = AnimalSex.objects.all()
    serializer_class = AnimalSexSerializer
    lookup_field = 'animal'

Leave a comment