Merge pull request #1441 from dustinfarris/null-serialization

TestCases and POST/PUT'ing serialized data that contains `None`
This commit is contained in:
Tom Christie 2014-02-28 09:27:27 +00:00
commit c3c69f4304
4 changed files with 50 additions and 3 deletions

View File

@ -33,6 +33,7 @@ class RelatedField(WritableField):
many_widget = widgets.SelectMultiple
form_field_class = forms.ChoiceField
many_form_field_class = forms.MultipleChoiceField
null_values = (None, '', 'None')
cache_choices = False
empty_label = None
@ -168,9 +169,9 @@ class RelatedField(WritableField):
return
value = [] if self.many else None
if value in (None, '') and self.required:
raise ValidationError(self.error_messages['required'])
elif value in (None, ''):
if value in self.null_values:
if self.required:
raise ValidationError(self.error_messages['required'])
into[(self.source or field_name)] = None
elif self.many:
into[(self.source or field_name)] = [self.from_native(item) for item in value]

View File

@ -0,0 +1,8 @@
from rest_framework import serializers
from rest_framework.tests.models import NullableForeignKeySource
class NullableFKSourceSerializer(serializers.ModelSerializer):
class Meta:
model = NullableForeignKeySource

View File

@ -0,0 +1,30 @@
from django.core.urlresolvers import reverse
from rest_framework.compat import patterns, url
from rest_framework.test import APITestCase
from rest_framework.tests.models import NullableForeignKeySource
from rest_framework.tests.serializers import NullableFKSourceSerializer
from rest_framework.tests.views import NullableFKSourceDetail
urlpatterns = patterns(
'',
url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'),
)
class NullableForeignKeyTests(APITestCase):
"""
DRF should be able to handle nullable foreign keys when a test
Client POST/PUT request is made with its own serialized object.
"""
urls = 'rest_framework.tests.test_nullable_fields'
def test_updating_object_with_null_fk(self):
obj = NullableForeignKeySource(name='example', target=None)
obj.save()
serialized_data = NullableFKSourceSerializer(obj).data
response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data)
self.assertEqual(response.data, serialized_data)

View File

@ -0,0 +1,8 @@
from rest_framework import generics
from rest_framework.tests.models import NullableForeignKeySource
from rest_framework.tests.serializers import NullableFKSourceSerializer
class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView):
model = NullableForeignKeySource
model_serializer_class = NullableFKSourceSerializer