Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 9 additions & 22 deletions dynamic_rest/fields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,20 +268,7 @@ def _is_dynamic(self):
)

def get_attribute(self, instance):
serializer = self.serializer
model = serializer.get_model()

# attempt to optimize by reading the related ID directly
# from the current instance rather than from the related object
if not self.kwargs['many'] and serializer.id_only():
return instance
elif model is not None:
try:
return getattr(instance, self.source)
except model.DoesNotExist:
return None
else:
return instance
return instance

def to_representation(self, instance):
"""Represent the relationship, either as an ID or object."""
Expand All @@ -296,18 +283,18 @@ def to_representation(self, instance):
# try the faster way first:
if hasattr(instance, source_id):
return getattr(instance, source_id)
elif model is not None:
# this is probably a one-to-one field, or a reverse related
# lookup, so let's look it up the slow way and let the
# serializer handle the id dereferencing
try:
instance = getattr(instance, source)
except model.DoesNotExist:
instance = None

# dereference ephemeral objects
if model is None:
instance = getattr(instance, source)
else:
# this is probably a one-to-one field, or a reverse related
# lookup, so let's look it up the slow way and let the
# serializer handle the id dereferencing
try:
instance = getattr(instance, source)
except model.DoesNotExist:
instance = None

if instance is None:
return None
Expand Down
27 changes: 26 additions & 1 deletion tests/test_serializers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import unittest
from mock import patch
from mock import patch, Mock
from collections import OrderedDict

from django.test import TestCase, override_settings
Expand Down Expand Up @@ -523,6 +523,31 @@ def test_post_processor(data):
data = serializer.data
self.assertTrue(data.get('post_processed'))

def test_to_representation_passed_model_instance(self):
mock_obj = Mock()

class GroupRelationField(DynamicRelationField):
def to_representation(self, instance):
mock_obj(instance)
# Dead men have no groups
if instance.is_dead:
return []
return super(GroupRelationField, self).to_representation(
instance)

class UserCustomGroupFieldSerializer(UserSerializer):
groups = GroupRelationField(GroupSerializer, many=True, embed=True)

user = User.objects.create(name='Dead', last_name='Mort', is_dead=True)
user.groups.add(*self.fixture.groups)

data = UserCustomGroupFieldSerializer(
user, request_fields={'groups': {'name': True}}
).data

assert data['groups'] == []
mock_obj.assert_called_once_with(user)


class TestListSerializer(TestCase):

Expand Down