From f07ba5f528e4c1eae68372307a31c4f5cc049556 Mon Sep 17 00:00:00 2001 From: Arnab Kumar Shil Date: Thu, 30 Mar 2023 01:18:15 +0200 Subject: [PATCH] Update relations.py 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. Reference: https://stackoverflow.com/questions/75878103/drf-attributeerror-when-trying-to-creating-a-instance-with-slugrelatedfield-and/75882424#75882424 --- rest_framework/relations.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 62da685fb..2f45f1de2 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -2,6 +2,7 @@ import contextlib import sys from collections import OrderedDict from urllib import parse +from operator import attrgetter from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.db.models import Manager @@ -464,7 +465,11 @@ class SlugRelatedField(RelatedField): self.fail('invalid') def to_representation(self, obj): - return getattr(obj, self.slug_field) + slug = self.slug_field + if "__" in slug: + # handling nested relationship defined by double underscore + slug = slug.replace('__', '.') + return attrgetter(obj, slug) class ManyRelatedField(Field):