[Solved]-DRF many-to-one reverse lookup

11๐Ÿ‘

โœ…

You need to add pet_set field to OwnerSerializer like this:

class PetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Pet
        fields = ("id", "name")

class OwnerSerializer(serializers.HyperlinkedModelSerializer):
    pet_set = PetSerializer(many=True, read_only=True)
    class Meta:
        model = Owner
        fields = ("id", "name", "pet_set")

This will work bacause many-to-one relation default reverse lookup name is <model>_set or pet_set in your case. You can change it by using related_name:

class Pet(models.Model):
    owner = models.ForeignKey(Owner, related_name='pets', on_delete=models.CASCADE)

In this case you can use pets name inside serializer:

class OwnerSerializer(serializers.HyperlinkedModelSerializer):
    pets = PetSerializer(many=True, read_only=True)

Now in OwnerListView you can use this new serializer:

class OwnerListView(ListAPIView):
    queryset = Owner.objects.all()
    serializer_class = OwnerSerializer
๐Ÿ‘คneverwalkaloner

3๐Ÿ‘

Change/ add your serializer.py as following

class PetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pet
        fields = ("id", "name")


class OwnerNewSerializer(serializers.ModelSerializer):
    pets = PetSerializer(many=True, source='pet_set')

    class Meta:
        model = Owner
        fields = ('id', 'name', 'pets')

and views.py

class OwnerAPI(viewsets.ModelViewSet):
    queryset = Owner.objects.all()
    serializer_class = OwnerNewSerialize
๐Ÿ‘คJPG

Leave a comment