Fix for pks returning as strings when set in pre_save. Fixes #482. Thanks to @n8agrin for the bug report.

This commit is contained in:
Tom Christie 2012-12-18 18:21:58 +00:00
parent 8f23b7f2f9
commit 6693d2d277
3 changed files with 18 additions and 12 deletions

View File

@ -113,6 +113,10 @@ class UpdateModelMixin(object):
slug_field = self.get_slug_field() slug_field = self.get_slug_field()
setattr(obj, slug_field, slug) setattr(obj, slug_field, slug)
# Ensure we clean the attributes so that we don't eg return integer
# pk using a string representation, as provided by the url conf kwarg.
obj.full_clean()
class DestroyModelMixin(object): class DestroyModelMixin(object):
""" """

View File

@ -497,25 +497,27 @@ class ModelSerializer(Serializer):
if instance is not None: if instance is not None:
for key, val in attrs.items(): for key, val in attrs.items():
setattr(instance, key, val) setattr(instance, key, val)
return instance
# Reverse relations else:
for (obj, model) in self.opts.model._meta.get_all_related_m2m_objects_with_model(): # Reverse relations
field_name = obj.field.related_query_name() for (obj, model) in self.opts.model._meta.get_all_related_m2m_objects_with_model():
if field_name in attrs: field_name = obj.field.related_query_name()
self.m2m_data[field_name] = attrs.pop(field_name) if field_name in attrs:
self.m2m_data[field_name] = attrs.pop(field_name)
# Forward relations # Forward relations
for field in self.opts.model._meta.many_to_many: for field in self.opts.model._meta.many_to_many:
if field.name in attrs: if field.name in attrs:
self.m2m_data[field.name] = attrs.pop(field.name) self.m2m_data[field.name] = attrs.pop(field.name)
instance = self.opts.model(**attrs)
instance = self.opts.model(**attrs)
try: try:
instance.full_clean(exclude=self.get_validation_exclusions()) instance.full_clean(exclude=self.get_validation_exclusions())
except ValidationError, err: except ValidationError, err:
self._errors = err.message_dict self._errors = err.message_dict
return None return None
return instance return instance
def save(self, save_m2m=True): def save(self, save_m2m=True):

View File

@ -175,7 +175,7 @@ class TestInstanceView(TestCase):
content = {'text': 'foobar'} content = {'text': 'foobar'}
request = factory.put('/1', json.dumps(content), request = factory.put('/1', json.dumps(content),
content_type='application/json') content_type='application/json')
response = self.view(request, pk=1).render() response = self.view(request, pk='1').render()
self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEquals(response.status_code, status.HTTP_200_OK)
self.assertEquals(response.data, {'id': 1, 'text': 'foobar'}) self.assertEquals(response.data, {'id': 1, 'text': 'foobar'})
updated = self.objects.get(id=1) updated = self.objects.get(id=1)