update docs where is mentioned. Added extra tests for pre_save behaviour.

This commit is contained in:
Marko Tibold 2012-12-13 22:57:35 +01:00
parent 497da7fc69
commit cf81ba8afb
2 changed files with 37 additions and 2 deletions

View File

@ -96,7 +96,11 @@ Now that snippets are associated with the user that created them, let's update o
owner = serializers.Field(source='owner.username')
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
**Note**: Make sure you also add `'owner',` to the list of excluded fields in the inner `Meta` class, like so:
exclude = ('owner', )
This makes the owner field not required, which is correct, because we set it in our `pre_save()` method.
This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
@ -188,4 +192,4 @@ We've now got a fairly fine-grained set of permissions on our Web API, and end p
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
[tut-5]: 5-relationships-and-hyperlinked-apis.md
[tut-5]: 5-relationships-and-hyperlinked-apis.md

View File

@ -301,3 +301,34 @@ class TestCreateModelWithAutoNowAddField(TestCase):
self.assertEquals(response.status_code, status.HTTP_201_CREATED)
created = self.objects.get(id=1)
self.assertEquals(created.content, 'foobar')
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
exclude = ('created', 'email')
class ViewUsingPreSave(generics.CreateAPIView):
serializer_class = CommentSerializer
model = Comment
def pre_save(self, obj):
obj.email = 'overriden@address.com'
class TestPreSave(TestCase):
def setUp(self):
self.view = ViewUsingPreSave.as_view()
def test_pre_save_gets_called(self):
"""
The email address is set at pre_save time.
"""
content = {'content': 'some content'}
request = factory.post('/', json.dumps(content),
content_type='application/json')
response = self.view(request).render()
self.assertEquals(response.status_code, status.HTTP_201_CREATED)
self.assertEquals(Comment.objects.get(pk=1).email, 'overriden@address.com')