This commit is contained in:
Nik Nyby 2017-09-15 15:49:41 +00:00 committed by GitHub
commit 47fe79d6a6
5 changed files with 21 additions and 21 deletions

View File

@ -90,7 +90,7 @@ The first thing we need to get started on our Web API is to provide a way of ser
class SnippetSerializer(serializers.Serializer): class SnippetSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True) pk = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False, allow_blank=True, max_length=100) title = serializers.CharField(required=False, allow_blank=True, max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'}) code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False) linenos = serializers.BooleanField(required=False)
@ -146,13 +146,13 @@ We've now got a few snippet instances to play with. Let's take a look at serial
serializer = SnippetSerializer(snippet) serializer = SnippetSerializer(snippet)
serializer.data serializer.data
# {'id': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'} # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`.
content = JSONRenderer().render(serializer.data) content = JSONRenderer().render(serializer.data)
content content
# '{"id": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}' # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into Python native datatypes... Deserialization is similar. First we parse a stream into Python native datatypes...
@ -177,7 +177,7 @@ We can also serialize querysets instead of model instances. To do so we simply
serializer = SnippetSerializer(Snippet.objects.all(), many=True) serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data serializer.data
# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])] # [OrderedDict([('pk', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]
## Using ModelSerializers ## Using ModelSerializers
@ -191,7 +191,7 @@ Open the file `snippets/serializers.py` again, and replace the `SnippetSerialize
class SnippetSerializer(serializers.ModelSerializer): class SnippetSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = Snippet model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style') fields = ('pk', 'title', 'code', 'linenos', 'language', 'style')
One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following: One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following:
@ -199,7 +199,7 @@ One nice property that serializers have is that you can inspect all the fields i
serializer = SnippetSerializer() serializer = SnippetSerializer()
print(repr(serializer)) print(repr(serializer))
# SnippetSerializer(): # SnippetSerializer():
# id = IntegerField(label='ID', read_only=True) # pk = IntegerField(label='PK', read_only=True)
# title = CharField(allow_blank=True, max_length=100, required=False) # title = CharField(allow_blank=True, max_length=100, required=False)
# code = CharField(style={'base_template': 'textarea.html'}) # code = CharField(style={'base_template': 'textarea.html'})
# linenos = BooleanField(required=False) # linenos = BooleanField(required=False)
@ -330,7 +330,7 @@ Finally, we can get a list of all of the snippets:
... ...
[ [
{ {
"id": 1, "pk": 1,
"title": "", "title": "",
"code": "foo = \"bar\"\n", "code": "foo = \"bar\"\n",
"linenos": false, "linenos": false,
@ -338,7 +338,7 @@ Finally, we can get a list of all of the snippets:
"style": "friendly" "style": "friendly"
}, },
{ {
"id": 2, "pk": 2,
"title": "", "title": "",
"code": "print \"hello, world\"\n", "code": "print \"hello, world\"\n",
"linenos": false, "linenos": false,
@ -347,14 +347,14 @@ Finally, we can get a list of all of the snippets:
} }
] ]
Or we can get a particular snippet by referencing its id: Or we can get a particular snippet by referencing its pk:
http http://127.0.0.1:8000/snippets/2/ http http://127.0.0.1:8000/snippets/2/
HTTP/1.1 200 OK HTTP/1.1 200 OK
... ...
{ {
"id": 2, "pk": 2,
"title": "", "title": "",
"code": "print \"hello, world\"\n", "code": "print \"hello, world\"\n",
"linenos": false, "linenos": false,

View File

@ -133,7 +133,7 @@ We can get a list of all of the snippets, as before.
... ...
[ [
{ {
"id": 1, "pk": 1,
"title": "", "title": "",
"code": "foo = \"bar\"\n", "code": "foo = \"bar\"\n",
"linenos": false, "linenos": false,
@ -141,7 +141,7 @@ We can get a list of all of the snippets, as before.
"style": "friendly" "style": "friendly"
}, },
{ {
"id": 2, "pk": 2,
"title": "", "title": "",
"code": "print \"hello, world\"\n", "code": "print \"hello, world\"\n",
"linenos": false, "linenos": false,
@ -166,7 +166,7 @@ Similarly, we can control the format of the request that we send, using the `Con
http --form POST http://127.0.0.1:8000/snippets/ code="print 123" http --form POST http://127.0.0.1:8000/snippets/ code="print 123"
{ {
"id": 3, "pk": 3,
"title": "", "title": "",
"code": "print 123", "code": "print 123",
"linenos": false, "linenos": false,
@ -178,7 +178,7 @@ Similarly, we can control the format of the request that we send, using the `Con
http --json POST http://127.0.0.1:8000/snippets/ code="print 456" http --json POST http://127.0.0.1:8000/snippets/ code="print 456"
{ {
"id": 4, "pk": 4,
"title": "", "title": "",
"code": "print 456", "code": "print 456",
"linenos": false, "linenos": false,

View File

@ -63,7 +63,7 @@ Now that we've got some users to work with, we'd better add representations of t
class Meta: class Meta:
model = User model = User
fields = ('id', 'username', 'snippets') fields = ('pk', 'username', 'snippets')
Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it. Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it.
@ -209,7 +209,7 @@ We can make a successful request by including the username and password of one o
http -a tom:password123 POST http://127.0.0.1:8000/snippets/ code="print 789" http -a tom:password123 POST http://127.0.0.1:8000/snippets/ code="print 789"
{ {
"id": 1, "pk": 1,
"owner": "tom", "owner": "tom",
"title": "foo", "title": "foo",
"code": "print 789", "code": "print 789",

View File

@ -67,7 +67,7 @@ In this case we'd like to use a hyperlinked style between entities. In order to
The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`: The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`:
* It does not include the `id` field by default. * It does not include the `pk` field by default.
* It includes a `url` field, using `HyperlinkedIdentityField`. * It includes a `url` field, using `HyperlinkedIdentityField`.
* Relationships use `HyperlinkedRelatedField`, * Relationships use `HyperlinkedRelatedField`,
instead of `PrimaryKeyRelatedField`. instead of `PrimaryKeyRelatedField`.
@ -80,7 +80,7 @@ We can easily re-write our existing serializers to use hyperlinking. In your `sn
class Meta: class Meta:
model = Snippet model = Snippet
fields = ('url', 'id', 'highlight', 'owner', fields = ('url', 'pk', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style') 'title', 'code', 'linenos', 'language', 'style')
@ -89,7 +89,7 @@ We can easily re-write our existing serializers to use hyperlinking. In your `sn
class Meta: class Meta:
model = User model = User
fields = ('url', 'id', 'username', 'snippets') fields = ('url', 'pk', 'username', 'snippets')
Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern. Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.

View File

@ -121,7 +121,7 @@ Let's try listing the existing snippets, using the command line client:
[ [
{ {
"url": "http://127.0.0.1:8000/snippets/1/", "url": "http://127.0.0.1:8000/snippets/1/",
"id": 1, "pk": 1,
"highlight": "http://127.0.0.1:8000/snippets/1/highlight/", "highlight": "http://127.0.0.1:8000/snippets/1/highlight/",
"owner": "lucy", "owner": "lucy",
"title": "Example", "title": "Example",
@ -180,7 +180,7 @@ snippet:
$ coreapi action snippets create --param title="Example" --param code="print('hello, world')" $ coreapi action snippets create --param title="Example" --param code="print('hello, world')"
{ {
"url": "http://127.0.0.1:8000/snippets/7/", "url": "http://127.0.0.1:8000/snippets/7/",
"id": 7, "pk": 7,
"highlight": "http://127.0.0.1:8000/snippets/7/highlight/", "highlight": "http://127.0.0.1:8000/snippets/7/highlight/",
"owner": "lucy", "owner": "lucy",
"title": "Example", "title": "Example",