You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -12,7 +12,7 @@ Serializer fields handle converting between primitive values and internal dataty
12
12
13
13
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
14
14
15
-
###- `required`
15
+
###`required`
16
16
17
17
Normally an error will be raised if a field is not supplied during deserialization.
18
18
Set to false if this field is not required to be present during deserialization.
@@ -21,7 +21,7 @@ Setting this to `False` also allows the object attribute or dictionary key to be
21
21
22
22
Defaults to `True`.
23
23
24
-
###- `default`
24
+
###`default`
25
25
26
26
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
27
27
@@ -31,31 +31,31 @@ When serializing the instance, default will be used if the the object attribute
31
31
32
32
Note that setting a `default` value implies that the field is not required. Enabling the arguments of the `default` keyword will set the` required` to `False`.
33
33
34
-
###- `label`
34
+
###`label`
35
35
36
36
A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
37
37
38
-
###- `validators`
38
+
###`validators`
39
39
40
40
A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should raise `serializers.ValidationError`.
41
41
42
-
###- `error_messages`
42
+
###`error_messages`
43
43
44
44
A dictionary of error codes to error messages.
45
45
46
46
---
47
47
48
48
# Fields
49
49
50
-
## - BooleanField
50
+
## BooleanField
51
51
52
52
When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.
53
53
54
54
**Signature:**`BooleanField()`
55
55
56
56
---
57
57
58
-
## - BooleanNullField
58
+
## BooleanNullField
59
59
60
60
A boolean representation that also accepts `None` as a valid value.
61
61
@@ -65,7 +65,7 @@ When using HTML encoded form input be aware that omitting a value will always be
65
65
66
66
---
67
67
68
-
## - CharField
68
+
## CharField
69
69
70
70
A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`.
71
71
@@ -78,7 +78,7 @@ A text representation. Optionally validates the text to be shorter than `max_len
78
78
79
79
---
80
80
81
-
## - IntegerField
81
+
## IntegerField
82
82
83
83
An integer representation.
84
84
@@ -89,7 +89,7 @@ An integer representation.
89
89
90
90
---
91
91
92
-
## - FloatField
92
+
## FloatField
93
93
94
94
A floating point representation.
95
95
@@ -102,7 +102,7 @@ A floating point representation.
102
102
103
103
# Date and time fields
104
104
105
-
## - DateTimeField
105
+
## DateTimeField
106
106
107
107
A date and time representation.
108
108
@@ -117,7 +117,7 @@ Format strings may either be [Python strftime formats][strftime] which explicitl
117
117
118
118
When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will determined by the renderer class.
119
119
120
-
## - DateField
120
+
## DateField
121
121
122
122
A date representation.
123
123
@@ -130,7 +130,7 @@ A date representation.
130
130
131
131
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`)
132
132
133
-
## - TimeField
133
+
## TimeField
134
134
135
135
A time representation.
136
136
@@ -147,7 +147,7 @@ Format strings may either be [Python strftime formats][strftime] which explicitl
147
147
148
148
# Composite fields
149
149
150
-
## - ListField
150
+
## ListField
151
151
152
152
A field class that validates a list of objects.
153
153
@@ -159,25 +159,25 @@ A field class that validates a list of objects.
159
159
-`allow_blank` - If set to` True`, an empty array should be considered valid. If set to `False`, an empty array is considered invalid and causes a validation error. The default is `False`.
160
160
161
161
For example, to validate a list of integers you might use something like the following:
The `ListField` class also supports a declarative style that allows you to write reusable list field classes.
168
-
169
-
class StringListField(serializers.ListField):
170
-
child = serializers.CharField()
171
-
168
+
```python
169
+
classStringListField(serializers.ListField):
170
+
child = serializers.CharField()
171
+
```
172
172
We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it.
173
173
174
-
## - JSONField
174
+
## JSONField
175
175
176
176
A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.
177
177
178
178
**Signature**: `JSONField()`
179
179
180
-
## - DictField
180
+
## DictField
181
181
182
182
A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values.
183
183
@@ -186,19 +186,19 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
186
186
-`child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
187
187
188
188
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
189
-
190
-
document = DictField(child=CharField())
191
-
189
+
```python
190
+
document = DictField(child=CharField())
191
+
```
192
192
You can also use the declarative style, as with `ListField`. For example:
193
-
194
-
class DocumentField(DictField):
195
-
child = CharField()
196
-
193
+
```python
194
+
classDocumentField(DictField):
195
+
child = CharField()
196
+
```
197
197
---
198
198
199
199
# Miscellaneous fields
200
200
201
-
## - SerializerMethodField
201
+
## SerializerMethodField
202
202
203
203
It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.
204
204
@@ -208,27 +208,27 @@ It gets its value by calling a method on the serializer class it is attached to.
208
208
-`method_name_pop` - The name of the method on the calling serializer during validation data. If not included this defaults to `pop_<field_name>`.
209
209
210
210
The serializer method referred to by the `method_name_get` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
The serializer method referenced by the `method_name_pop` argument must take one argument (in addition to` self`), which is the value to process and validate. It must return whatever you want to include in the validated view of the data. For example:
222
+
```python
223
+
from datetime.datetime import now
224
+
from rest_framework import serializers
222
225
223
-
from datetime.datetime import now
224
-
from rest_framework import serializers
225
-
226
-
class UserSerializer(serializers.Serializer):
227
-
rgb = serializers.SerializerMethodField()
228
-
229
-
def pop_rgb(self, data):
230
-
return data.split(';')[1:3]
226
+
classUserSerializer(serializers.Serializer):
227
+
rgb = serializers.SerializerMethodField()
231
228
229
+
defpop_rgb(self, data):
230
+
return data.split(';')[1:3]
231
+
```
232
232
---
233
233
234
234
# Custom fields
@@ -246,91 +246,91 @@ The `to_internal_value()` method is called to restore a primitive datatype into
246
246
### A Basic Custom Field
247
247
248
248
Let's look at an example of serializing a class that represents an RGB color value:
249
+
```python
250
+
classColor(object):
251
+
"""
252
+
A color represented in the RGB colorspace.
249
253
250
-
class Color(object):
251
-
"""
252
-
A color represented in the RGB colorspace.
253
-
254
-
"""
255
-
def __init__(self, red, green, blue):
256
-
assert(red >= 0 and green >= 0 and blue >= 0)
257
-
assert(red < 256 and green < 256 and blue < 256)
258
-
self.red, self.green, self.blue = red, green, blue
259
-
260
-
class ColorField(serializers.Field):
261
-
"""
262
-
Color objects are serialized into 'rgb(#, #, #)' notation.
254
+
"""
255
+
def__init__(self, red, green, blue):
256
+
assert(red >=0and green >=0and blue >=0)
257
+
assert(red <256and green <256and blue <256)
258
+
self.red, self.green, self.blue = red, green, blue
red, green, blue = [int(col) for col in data.split(',')]
271
+
return Color(red, green, blue)
272
+
```
273
273
By default field values are treated as mapping to an attribute on the object or key Mapping collection. If you need to customize how the field value is accessed and set you need to override `.get_attribute()`.
274
274
275
275
As an example, let's create a field that can be used to represent the class name of the object being serialized:
276
+
```python
277
+
classClassNameField(serializers.Field):
278
+
defget_attribute(self, instance):
279
+
# We pass the object instance onto `to_representation`,
280
+
# not just the field attribute.
281
+
return instance
282
+
283
+
defto_representation(self, value):
284
+
"""
285
+
Serialize the value's class name.
276
286
277
-
class ClassNameField(serializers.Field):
278
-
def get_attribute(self, instance):
279
-
# We pass the object instance onto `to_representation`,
280
-
# not just the field attribute.
281
-
return instance
282
-
283
-
def to_representation(self, value):
284
-
"""
285
-
Serialize the value's class name.
286
-
287
-
"""
288
-
return value.__class__.__name__
289
-
287
+
"""
288
+
return value.__class__.__name__
289
+
```
290
290
### Raising validation errors
291
291
292
292
Our `ColorField` class above currently does not perform any data validation.
293
293
To indicate invalid data, we should raise a `serializers.ValidationError`, like so:
294
+
```python
295
+
defto_internal_value(self, data):
296
+
ifnotisinstance(data, six.text_type):
297
+
msg ='Incorrect type. Expected a string, but got %s'
298
+
raise ValidationError(msg %type(data).__name__)
294
299
295
-
def to_internal_value(self, data):
296
-
if not isinstance(data, six.text_type):
297
-
msg = 'Incorrect type. Expected a string, but got %s'
0 commit comments