Handle Nested Relation in SlugRelatedField when many=False by ruddra · Pull Request #8922 · encode/django-rest-framework (original) (raw)

Currently if you define the slug field as a nested relationship in a SlugRelatedField while many=False, it will cause an attribute error. For example:

For this code:

class SomeSerializer(serializers.ModelSerializer):
    some_field= serializers.SlugRelatedField(queryset=SomeClass.objects.all(), slug_field="foo__bar")

The POST request (or save operation) should work just fine, but if you use GET, then it will fail with Attribute error:

AttributeError: 'SomeClass' object has no attribute 'foo__bar'

Thus I am handling nested relation here. Apart from that, I have added test cases regarding nested relations.

Reference: https://stackoverflow.com/questions/75878103/drf-attributeerror-when-trying-to-creating-a-instance-with-slugrelatedfield-and/75882424