Home > Mobile >  How to list all items based on foreign key pk Django Rest Framework
How to list all items based on foreign key pk Django Rest Framework

Time:01-22

i want to list all the instanced that are saved to a certain Animal. Let's say a dog has id 3 and i have got 2 instances of dog sexes but when i get the request from animal/3/sex i only get one instance not 2. I tried using many=True to serializers.PrimaryKeyRelatedField but it shows me that 'Animal is not iterable'. Do you have any idea how to do it?

class AnimalSex(models.Model):
    name = models.CharField(max_length=256)
    slug = models.SlugField(max_length=128, unique=True, null=False, editable=False)
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False)

VIEWS

class MyAnimalSex(generics.RetrieveAPIView):

    queryset = AnimalSex.objects.all()
    serializer_class = AnimalSexSerializer
    lookup_field = 'pk'

SERIALIZER

class AnimalSexSerializer(serializers.ModelSerializer):

    animal = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = AnimalSex
        fields = ('name', 'slug', 'animal',)

URL

    path('animal/<int:pk>/sex', MyAnimalSex.as_view()),

CodePudding user response:

In that case you probably want to use a ListAPIView 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']
        )
  •  Tags:  
  • Related