Debian Codegraph @

docs/api-guide/fields.md

raw
1 ---
2 source:
3 - fields.py
4 ---
5
6 # Serializer fields
7
8 > Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.
9 >
10 > — [Django documentation][cite]
11
12 Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
13
14 !!! note
15 The serializer fields are declared in `fields.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
16
17 ## Core arguments
18
19 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:
20
21 ### `read_only`
22
23 Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
24
25 Set this to `True` to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
26
27 Defaults to `False`
28
29 ### `write_only`
30
31 Set this to `True` to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
32
33 Defaults to `False`
34
35 ### `required`
36
37 Normally an error will be raised if a field is not supplied during deserialization.
38 Set to false if this field is not required to be present during deserialization.
39
40 Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
41
42 Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer), the default value will be `False` when you have specified a `default`, or when the corresponding `Model` field has `blank=True` or `null=True` and is not part of a unique constraint at the same time. (Note that without a `default` value, [unique constraints will cause the field to be required](https://www.django-rest-framework.org/api-guide/validators/#optional-fields).)
43
44 ### `default`
45
46 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 behavior is to not populate the attribute at all.
47
48 The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
49
50 May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `requires_context = True` attribute, then the serializer field will be passed as an argument.
51
52 For example:
53
54 class CurrentUserDefault:
55 """
56 May be applied as a `default=...` value on a serializer field.
57 Returns the current user.
58 """
59 requires_context = True
60
61 def __call__(self, serializer_field):
62 return serializer_field.context['request'].user
63
64 When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance.
65
66 Note that setting a `default` value implies that the field is not required. Combining `default` with `required=True` is invalid and will raise an error. An explicit `required=False` alongside `default` is allowed, but redundant.
67
68 ### `allow_null`
69
70 Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value.
71
72 Note that, without an explicit `default`, setting this argument to `True` will imply a `default` value of `null` for serialization output, but does not imply a default for input deserialization.
73
74 Defaults to `False`
75
76 ### `source`
77
78 The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
79
80 When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
81
82 class CommentSerializer(serializers.Serializer):
83 email = serializers.EmailField(source="user.email")
84
85 This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
86
87 Also note that when dotted notation is used, after serializer validation the `.validated_data` attribute will _not_ include a flat `"<fieldname>": <value>` item. Instead, it will include a nested dictionary derived by expanding the dotted path value of the `source` argument. So, for the previous serializer example, `.validated_data` would be:
88
89 {
90 "user": {
91 "email": ...
92 }
93 }
94
95 instead of:
96
97 {
98 "email": ...
99 }
100
101 This works this way because, in DRF's philosophy, the `.data` attribute represents the external API representation (where key names equal field names), while the `.validated_data` attribute represents the internal object structure (where the nesting and key names follow the `source` path).
102
103 The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
104
105 Defaults to the name of the field.
106
107 ### `validators`
108
109 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 typically raise `serializers.ValidationError`, but Django's built-in `ValidationError` is also supported for compatibility with validators defined in the Django codebase or third party Django packages.
110
111 ### `error_messages`
112
113 A dictionary of error codes to error messages.
114
115 ### `label`
116
117 A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
118
119 ### `help_text`
120
121 A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
122
123 ### `initial`
124
125 A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as
126 you may do with any regular Django `Field`:
127
128 import datetime
129 from rest_framework import serializers
130 class ExampleSerializer(serializers.Serializer):
131 day = serializers.DateField(initial=datetime.date.today)
132
133 ### `style`
134
135 A dictionary of key-value pairs that can be used to control how renderers should render the field.
136
137 Two examples here are `'input_type'` and `'base_template'`:
138
139 # Use <input type="password"> for the input.
140 password = serializers.CharField(
141 style={'input_type': 'password'}
142 )
143
144 # Use a radio input instead of a select input.
145 color_channel = serializers.ChoiceField(
146 choices=['red', 'green', 'blue'],
147 style={'base_template': 'radio.html'}
148 )
149
150 For more details see the [HTML & Forms][html-and-forms] documentation.
151
152 ---
153
154 ## Boolean fields
155
156 ### BooleanField
157
158 A boolean representation.
159
160 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.
161
162 Note that Django 2.1 removed the `blank` kwarg from `models.BooleanField`.
163 Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
164 since Django 2.1 default `serializers.BooleanField` instances will be generated
165 without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
166 previous versions of Django, default `BooleanField` instances will be generated
167 with a `required=False` option. If you want to control this behavior manually,
168 explicitly declare the `BooleanField` on the serializer class, or use the
169 `extra_kwargs` option to set the `required` flag.
170
171 Corresponds to `django.db.models.fields.BooleanField`.
172
173 **Signature:** `BooleanField()`
174
175 ---
176
177 ## String fields
178
179 ### CharField
180
181 A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`.
182
183 Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`.
184
185 **Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
186
187 * `max_length` - Validates that the input contains no more than this number of characters.
188 * `min_length` - Validates that the input contains no fewer than this number of characters.
189 * `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
190 * `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
191
192 The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
193
194 ### EmailField
195
196 A text representation, validates the text to be a valid email address.
197
198 Corresponds to `django.db.models.fields.EmailField`
199
200 **Signature:** `EmailField(max_length=None, min_length=None, allow_blank=False)`
201
202 ### RegexField
203
204 A text representation, that validates the given value matches against a certain regular expression.
205
206 Corresponds to `django.forms.fields.RegexField`.
207
208 **Signature:** `RegexField(regex, max_length=None, min_length=None, allow_blank=False)`
209
210 The mandatory `regex` argument may either be a string, or a compiled python regular expression object.
211
212 Uses Django's `django.core.validators.RegexValidator` for validation.
213
214 ### SlugField
215
216 A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`.
217
218 Corresponds to `django.db.models.fields.SlugField`.
219
220 **Signature:** `SlugField(max_length=50, min_length=None, allow_blank=False)`
221
222 ### URLField
223
224 A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http://<host>/<path>`.
225
226 Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
227
228 **Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)`
229
230 ### UUIDField
231
232 A field that ensures the input is a valid UUID string. The `to_internal_value` method will return a `uuid.UUID` instance. On output the field will return a string in the canonical hyphenated format, for example:
233
234 "de305d54-75b4-431b-adb2-eb6b9e546013"
235
236 **Signature:** `UUIDField(format='hex_verbose')`
237
238 * `format`: Determines the representation format of the uuid value
239 * `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
240 * `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
241 * `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
242 * `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
243 Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
244
245 ### FilePathField
246
247 A field whose choices are limited to the filenames in a certain directory on the filesystem
248
249 Corresponds to `django.forms.fields.FilePathField`.
250
251 **Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
252
253 * `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
254 * `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
255 * `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
256 * `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
257 * `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
258
259 ### IPAddressField
260
261 A field that ensures the input is a valid IPv4 or IPv6 string.
262
263 Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.GenericIPAddressField`.
264
265 **Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
266
267 * `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case-insensitive.
268 * `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
269
270 ---
271
272 ## Numeric fields
273
274 ### IntegerField
275
276 An integer representation.
277
278 Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`.
279
280 **Signature**: `IntegerField(max_value=None, min_value=None)`
281
282 * `max_value` Validate that the number provided is no greater than this value.
283 * `min_value` Validate that the number provided is no less than this value.
284
285 ### BigIntegerField
286
287 A biginteger representation.
288
289 Corresponds to `django.db.models.fields.BigIntegerField`.
290
291 **Signature**: `BigIntegerField(max_value=None, min_value=None, coerce_to_string=None)`
292
293 * `max_value` Validate that the number provided is no greater than this value.
294 * `min_value` Validate that the number provided is no less than this value.
295 * `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `BigInteger` objects should be returned. Defaults to the same value as the `COERCE_BIGINT_TO_STRING` settings key, which will be `False` unless overridden. If `BigInteger` objects are returned by the serializer, then the final output format will be determined by the renderer.
296
297 ### FloatField
298
299 A floating point representation.
300
301 Corresponds to `django.db.models.fields.FloatField`.
302
303 **Signature**: `FloatField(max_value=None, min_value=None)`
304
305 * `max_value` Validate that the number provided is no greater than this value.
306 * `min_value` Validate that the number provided is no less than this value.
307
308 ### DecimalField
309
310 A decimal representation, represented in Python by a `Decimal` instance.
311
312 Corresponds to `django.db.models.fields.DecimalField`.
313
314 **Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
315
316 * `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
317 * `decimal_places` The number of decimal places to store with the number.
318 * `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
319 * `max_value` Validate that the number provided is no greater than this value. Should be an integer or `Decimal` object.
320 * `min_value` Validate that the number provided is no less than this value. Should be an integer or `Decimal` object.
321 * `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
322 * `rounding` Sets the rounding mode used when quantizing to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
323 * `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to `False`.
324
325 #### Example usage
326
327 To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
328
329 serializers.DecimalField(max_digits=5, decimal_places=2)
330
331 And to validate numbers up to anything less than one billion with a resolution of 10 decimal places:
332
333 serializers.DecimalField(max_digits=19, decimal_places=10)
334
335 ---
336
337 ## Date and time fields
338
339 ### DateTimeField
340
341 A date and time representation.
342
343 Corresponds to `django.db.models.fields.DateTimeField`.
344
345 **Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)`
346
347 * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer.
348 * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
349 * `default_timezone` - A `tzinfo` subclass (`zoneinfo`) representing the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive.
350
351 #### `DateTimeField` format strings.
352
353 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 datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
354
355 When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will be determined by the renderer class.
356
357 #### `auto_now` and `auto_now_add` model fields.
358
359 When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default.
360
361 If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example:
362
363 class CommentSerializer(serializers.ModelSerializer):
364 created = serializers.DateTimeField()
365
366 class Meta:
367 model = Comment
368
369 ### DateField
370
371 A date representation.
372
373 Corresponds to `django.db.models.fields.DateField`
374
375 **Signature:** `DateField(format=api_settings.DATE_FORMAT, input_formats=None)`
376
377 * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer.
378 * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
379
380 #### `DateField` format strings
381
382 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'`)
383
384 ### TimeField
385
386 A time representation.
387
388 Corresponds to `django.db.models.fields.TimeField`
389
390 **Signature:** `TimeField(format=api_settings.TIME_FORMAT, input_formats=None)`
391
392 * `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer.
393 * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
394
395 #### `TimeField` format strings
396
397 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 times should be used. (eg `'12:34:56.000000'`)
398
399 ### DurationField
400
401 A Duration representation.
402 Corresponds to `django.db.models.fields.DurationField`
403
404 The `validated_data` for these fields will contain a `datetime.timedelta` instance.
405
406 **Signature:** `DurationField(format=api_settings.DURATION_FORMAT, max_value=None, min_value=None)`
407
408 * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DURATION_FORMAT` settings key, which will be `'django'` unless set. Formats are described below. Setting this value to `None` indicates that Python `timedelta` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer.
409 * `max_value` Validate that the duration provided is no greater than this value.
410 * `min_value` Validate that the duration provided is no less than this value.
411
412 #### `DurationField` formats
413 Format may either be the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style intervals should be used (eg `'P4DT1H15M20S'`), or `'django'` which indicates that Django interval format `'[DD] [HH:[MM:]]ss[.uuuuuu]'` should be used (eg: `'4 1:15:20'`).
414
415 ---
416
417 ## Choice selection fields
418
419 ### ChoiceField
420
421 A field that can accept a value out of a limited set of choices.
422
423 Used by `ModelSerializer` to automatically generate fields if the corresponding model field includes a `choices=…` argument.
424
425 **Signature:** `ChoiceField(choices)`
426
427 * `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
428 * `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
429 * `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
430 * `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
431
432 Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
433
434 ### MultipleChoiceField
435
436 A field that can accept a list of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_value` returns a `list` containing the selected values, deduplicated.
437
438 **Signature:** `MultipleChoiceField(choices)`
439
440 * `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
441 * `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
442 * `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
443 * `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
444
445 As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
446
447 ---
448
449 ## File upload fields
450
451 !!! note
452 The `FileField` and `ImageField` classes are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads.
453 Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
454
455 ### FileField
456
457 A file representation. Performs Django's standard FileField validation.
458
459 Corresponds to `django.forms.fields.FileField`.
460
461 **Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
462
463 * `max_length` - Designates the maximum length for the file name.
464 * `allow_empty_file` - Designates if empty files are allowed.
465 * `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
466
467 ### ImageField
468
469 An image representation. Validates the uploaded file content as matching a known image format.
470
471 Corresponds to `django.forms.fields.ImageField`.
472
473 **Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
474
475 * `max_length` - Designates the maximum length for the file name.
476 * `allow_empty_file` - Designates if empty files are allowed.
477 * `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
478
479 Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
480
481 ---
482
483 ## Composite fields
484
485 ### ListField
486
487 A field class that validates a list of objects.
488
489 **Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
490
491 * `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
492 * `allow_empty` - Designates if empty lists are allowed.
493 * `min_length` - Validates that the list contains no fewer than this number of elements.
494 * `max_length` - Validates that the list contains no more than this number of elements.
495
496 For example, to validate a list of integers you might use something like the following:
497
498 scores = serializers.ListField(
499 child=serializers.IntegerField(min_value=0, max_value=100)
500 )
501
502 The `ListField` class also supports a declarative style that allows you to write reusable list field classes.
503
504 class StringListField(serializers.ListField):
505 child = serializers.CharField()
506
507 We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it.
508
509 ### DictField
510
511 A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values.
512
513 **Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
514
515 * `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.
516 * `allow_empty` - Designates if empty dictionaries are allowed.
517
518 For example, to create a field that validates a mapping of strings to strings, you would write something like this:
519
520 document = DictField(child=CharField())
521
522 You can also use the declarative style, as with `ListField`. For example:
523
524 class DocumentField(DictField):
525 child = CharField()
526
527 ### HStoreField
528
529 A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`.
530
531 **Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
532
533 * `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
534 * `allow_empty` - Designates if empty dictionaries are allowed.
535
536 Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
537
538 ### JSONField
539
540 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.
541
542 **Signature**: `JSONField(binary, encoder)`
543
544 * `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
545 * `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
546
547 ---
548
549 ## Miscellaneous fields
550
551 ### ReadOnlyField
552
553 A field class that simply returns the value of the field without modification.
554
555 This field is used by default with `ModelSerializer` when including field names that relate to an attribute rather than a model field.
556
557 **Signature**: `ReadOnlyField()`
558
559 For example, if `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`:
560
561 class AccountSerializer(serializers.ModelSerializer):
562 class Meta:
563 model = Account
564 fields = ['id', 'account_name', 'has_expired']
565
566 ### HiddenField
567
568 A field class that does not take a value based on user input, but instead takes its value from a default value or callable.
569
570 **Signature**: `HiddenField()`
571
572 For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:
573
574 modified = serializers.HiddenField(default=timezone.now)
575
576 The `HiddenField` class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.
577
578 For further examples on `HiddenField` see the [validators](validators.md) documentation.
579
580 !!! note
581 `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
582
583 ### ModelField
584
585 A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
586
587 This field is used by `ModelSerializer` to correspond to custom model field classes.
588
589 **Signature:** `ModelField(model_field=<Django ModelField instance>)`
590
591 The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))`
592
593 ### SerializerMethodField
594
595 This is a read-only field. 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.
596
597 **Signature**: `SerializerMethodField(method_name=None)`
598
599 * `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
600
601 The serializer method referred to by the `method_name` 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:
602
603 from django.contrib.auth.models import User
604 from django.utils.timezone import now
605 from rest_framework import serializers
606
607 class UserSerializer(serializers.ModelSerializer):
608 days_since_joined = serializers.SerializerMethodField()
609
610 class Meta:
611 model = User
612 fields = '__all__'
613
614 def get_days_since_joined(self, obj):
615 return (now() - obj.date_joined).days
616
617 ---
618
619 ## Custom fields
620
621 If you want to create a custom field, you'll need to subclass `Field` and then override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, `date`/`time`/`datetime` or `None`. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.
622
623 The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype.
624
625 The `.to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid.
626
627 ### Examples
628
629 #### A Basic Custom Field
630
631 Let's look at an example of serializing a class that represents an RGB color value:
632
633 class Color:
634 """
635 A color represented in the RGB colorspace.
636 """
637 def __init__(self, red, green, blue):
638 assert(red >= 0 and green >= 0 and blue >= 0)
639 assert(red < 256 and green < 256 and blue < 256)
640 self.red, self.green, self.blue = red, green, blue
641
642 class ColorField(serializers.Field):
643 """
644 Color objects are serialized into 'rgb(#, #, #)' notation.
645 """
646 def to_representation(self, value):
647 return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)
648
649 def to_internal_value(self, data):
650 data = data.strip('rgb(').rstrip(')')
651 red, green, blue = [int(col) for col in data.split(',')]
652 return Color(red, green, blue)
653
654 By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.get_attribute()` and/or `.get_value()`.
655
656 As an example, let's create a field that can be used to represent the class name of the object being serialized:
657
658 class ClassNameField(serializers.Field):
659 def get_attribute(self, instance):
660 # We pass the object instance onto `to_representation`,
661 # not just the field attribute.
662 return instance
663
664 def to_representation(self, value):
665 """
666 Serialize the value's class name.
667 """
668 return value.__class__.__name__
669
670 #### Raising validation errors
671
672 Our `ColorField` class above currently does not perform any data validation.
673 To indicate invalid data, we should raise a `serializers.ValidationError`, like so:
674
675 def to_internal_value(self, data):
676 if not isinstance(data, str):
677 msg = 'Incorrect type. Expected a string, but got %s'
678 raise ValidationError(msg % type(data).__name__)
679
680 if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
681 raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')
682
683 data = data.strip('rgb(').rstrip(')')
684 red, green, blue = [int(col) for col in data.split(',')]
685
686 if any([col > 255 or col < 0 for col in (red, green, blue)]):
687 raise ValidationError('Value out of range. Must be between 0 and 255.')
688
689 return Color(red, green, blue)
690
691 The `.fail()` method is a shortcut for raising `ValidationError` that takes a message string from the `error_messages` dictionary. For example:
692
693 default_error_messages = {
694 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',
695 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',
696 'out_of_range': 'Value out of range. Must be between 0 and 255.'
697 }
698
699 def to_internal_value(self, data):
700 if not isinstance(data, str):
701 self.fail('incorrect_type', input_type=type(data).__name__)
702
703 if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
704 self.fail('incorrect_format')
705
706 data = data.strip('rgb(').rstrip(')')
707 red, green, blue = [int(col) for col in data.split(',')]
708
709 if any([col > 255 or col < 0 for col in (red, green, blue)]):
710 self.fail('out_of_range')
711
712 return Color(red, green, blue)
713
714 This style keeps your error messages cleaner and more separated from your code, and should be preferred.
715
716 #### Using `source='*'`
717
718 Here we'll take an example of a _flat_ `DataPoint` model with `x_coordinate` and `y_coordinate` attributes.
719
720 class DataPoint(models.Model):
721 label = models.CharField(max_length=50)
722 x_coordinate = models.SmallIntegerField()
723 y_coordinate = models.SmallIntegerField()
724
725 Using a custom field and `source='*'` we can provide a nested representation of
726 the coordinate pair:
727
728 class CoordinateField(serializers.Field):
729
730 def to_representation(self, value):
731 ret = {
732 "x": value.x_coordinate,
733 "y": value.y_coordinate
734 }
735 return ret
736
737 def to_internal_value(self, data):
738 ret = {
739 "x_coordinate": data["x"],
740 "y_coordinate": data["y"],
741 }
742 return ret
743
744
745 class DataPointSerializer(serializers.ModelSerializer):
746 coordinates = CoordinateField(source='*')
747
748 class Meta:
749 model = DataPoint
750 fields = ['label', 'coordinates']
751
752 Note that this example doesn't handle validation. Partly for that reason, in a
753 real project, the coordinate nesting might be better handled with a nested serializer
754 using `source='*'`, with two `IntegerField` instances, each with their own `source`
755 pointing to the relevant field.
756
757 The key points from the example, though, are:
758
759 * `to_representation` is passed the entire `DataPoint` object and must map from that
760 to the desired output.
761
762 >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)
763 >>> out_serializer = DataPointSerializer(instance)
764 >>> out_serializer.data
765 ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])
766
767 * Unless our field is to be read-only, `to_internal_value` must map back to a dict
768 suitable for updating our target object. With `source='*'`, the return from
769 `to_internal_value` will update the root validated data dictionary, rather than a single key.
770
771 >>> data = {
772 ... "label": "Second Example",
773 ... "coordinates": {
774 ... "x": 3,
775 ... "y": 4,
776 ... }
777 ... }
778 >>> in_serializer = DataPointSerializer(data=data)
779 >>> in_serializer.is_valid()
780 True
781 >>> in_serializer.validated_data
782 OrderedDict([('label', 'Second Example'),
783 ('y_coordinate', 4),
784 ('x_coordinate', 3)])
785
786 For completeness let's do the same thing again but with the nested serializer
787 approach suggested above:
788
789 class NestedCoordinateSerializer(serializers.Serializer):
790 x = serializers.IntegerField(source='x_coordinate')
791 y = serializers.IntegerField(source='y_coordinate')
792
793
794 class DataPointSerializer(serializers.ModelSerializer):
795 coordinates = NestedCoordinateSerializer(source='*')
796
797 class Meta:
798 model = DataPoint
799 fields = ['label', 'coordinates']
800
801 Here the mapping between the target and source attribute pairs (`x` and
802 `x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
803 declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
804
805 Our new `DataPointSerializer` exhibits the same behavior as the custom field
806 approach.
807
808 Serializing:
809
810 >>> out_serializer = DataPointSerializer(instance)
811 >>> out_serializer.data
812 ReturnDict([('label', 'testing'),
813 ('coordinates', OrderedDict([('x', 1), ('y', 2)]))])
814
815 Deserializing:
816
817 >>> in_serializer = DataPointSerializer(data=data)
818 >>> in_serializer.is_valid()
819 True
820 >>> in_serializer.validated_data
821 OrderedDict([('label', 'still testing'),
822 ('x_coordinate', 3),
823 ('y_coordinate', 4)])
824
825 But we also get the built-in validation for free:
826
827 >>> invalid_data = {
828 ... "label": "still testing",
829 ... "coordinates": {
830 ... "x": 'a',
831 ... "y": 'b',
832 ... }
833 ... }
834 >>> invalid_serializer = DataPointSerializer(data=invalid_data)
835 >>> invalid_serializer.is_valid()
836 False
837 >>> invalid_serializer.errors
838 ReturnDict([('coordinates',
839 {'x': ['A valid integer is required.'],
840 'y': ['A valid integer is required.']})])
841
842 For this reason, the nested serializer approach would be the first to try. You
843 would use the custom field approach when the nested serializer becomes infeasible
844 or overly complex.
845
846
847 ## Third party packages
848
849 The following third party packages are also available.
850
851 ### DRF Compound Fields
852
853 The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.
854
855 ### DRF Extra Fields
856
857 The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes.
858
859 ### djangorestframework-recursive
860
861 the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures
862
863 ### django-rest-framework-gis
864
865 The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
866
867 [cite]: https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.cleaned_data
868 [html-and-forms]: ../topics/html-and-forms.md
869 [FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
870 [strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
871 [iso8601]: https://www.w3.org/TR/NOTE-datetime
872 [drf-compound-fields]: https://drf-compound-fields.readthedocs.io
873 [drf-extra-fields]: https://github.com/Hipo/drf-extra-fields
874 [djangorestframework-recursive]: https://github.com/heywbj/django-rest-framework-recursive
875 [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
876 [python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes
877 [django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone
878 [django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related