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
This commit is contained in:
Arnab Kumar Shil 2023-03-30 01:18:15 +02:00 committed by GitHub
parent 6b73acc173
commit f07ba5f528
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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):