mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-23 06:29:58 +03:00
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:
parent
6b73acc173
commit
f07ba5f528
|
@ -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):
|
||||
|
|
Loading…
Reference in New Issue
Block a user