Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()),

>Solution :

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']
        )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading