Repository: encode/django-rest-framework

Issue:
HyperlinkedRelatedField breaks for Null related field values
If a model's related field allows nulls and has a null value, HyperlinkedRelatedField throws an error.

File "... /python2.7/site-packages/rest_framework/fields.py", line 521, in to_native
kwargs = {self.pk_url_kwarg: obj.pk}
AttributeError: 'NoneType' object has no attribute 'pk'

If appears that the value is null that is sent as "obj".  In HyperlinkedRelatedField.to_native, if obj is None, shouldn't it just return None so the returned data is null?



Discussion:
+1.  Yes, that'd be sensible.

I think this may be related with bug #384...


Resolving patch:
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -522,7 +522,10 @@ def to_native(self, obj):
         view_name = self.view_name
         request = self.context.get('request', None)
         format = self.format or self.context.get('format', None)
-        kwargs = {self.pk_url_kwarg: obj.pk}
+        pk = getattr(obj, 'pk', None)
+        if pk is None:
+            return
+        kwargs = {self.pk_url_kwarg: pk}
         try:
             return reverse(view_name, kwargs=kwargs, request=request, format=format)
         except:


Test patch:
diff --git a/rest_framework/tests/hyperlinkedserializers.py b/rest_framework/tests/hyperlinkedserializers.py
--- a/rest_framework/tests/hyperlinkedserializers.py
+++ b/rest_framework/tests/hyperlinkedserializers.py
@@ -2,7 +2,7 @@
 from django.test import TestCase
 from django.test.client import RequestFactory
 from rest_framework import generics, status, serializers
-from rest_framework.tests.models import Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment, Album, Photo
+from rest_framework.tests.models import Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment, Album, Photo, OptionalRelationModel
 
 factory = RequestFactory()
 
@@ -67,6 +67,11 @@ class AlbumDetail(generics.RetrieveAPIView):
     model = Album
 
 
+class OptionalRelationDetail(generics.RetrieveAPIView):
+    model = OptionalRelationModel
+    model_serializer_class = serializers.HyperlinkedModelSerializer
+
+
 urlpatterns = patterns('',
     url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'),
     url(r'^basic/(?P<pk>\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'),
@@ -76,7 +81,8 @@ class AlbumDetail(generics.RetrieveAPIView):
     url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'),
     url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'),
     url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'),
-    url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list')
+    url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'),
+    url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'),
 )
 
 
@@ -211,3 +217,26 @@ def test_create_photo(self):
         self.assertEqual(response.status_code, status.HTTP_201_CREATED)
         self.assertEqual(self.post.photo_set.count(), 1)
         self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo')
+
+
+class TestOptionalRelationHyperlinkedView(TestCase):
+    urls = 'rest_framework.tests.hyperlinkedserializers'
+
+    def setUp(self):
+        """
+        Create 1 OptionalRelationModel intances.
+        """
+        OptionalRelationModel().save()
+        self.objects = OptionalRelationModel.objects
+        self.detail_view = OptionalRelationDetail.as_view()
+        self.data = {"url": "http://testserver/optionalrelation/1/", "other": None}
+
+    def test_get_detail_view(self):
+        """
+        GET requests to RetrieveAPIView with optional relations should return None
+        for non existing relations.
+        """
+        request = factory.get('/optionalrelationmodel-detail/1')
+        response = self.detail_view(request, pk=1).render()
+        self.assertEquals(response.status_code, status.HTTP_200_OK)
+        self.assertEquals(response.data, self.data)
diff --git a/rest_framework/tests/models.py b/rest_framework/tests/models.py
--- a/rest_framework/tests/models.py
+++ b/rest_framework/tests/models.py
@@ -149,3 +149,8 @@ def info(self):
 # Model for issue #324
 class BlankFieldModel(RESTFrameworkModel):
     title = models.CharField(max_length=100, blank=True)
+
+
+# Model for issue #380
+class OptionalRelationModel(RESTFrameworkModel):
+    other = models.ForeignKey('OptionalRelationModel', blank=True, null=True)