diff options
| author | Tom Christie | 2015-01-05 14:32:12 +0000 |
|---|---|---|
| committer | Tom Christie | 2015-01-05 14:32:12 +0000 |
| commit | b6ca7248ebcf95a95e1911aa0b130f653b8bf690 (patch) | |
| tree | 3da53011f0e215da5e13efcaf39223f88edfefce /rest_framework | |
| parent | 8cf37449715c32c4a692667814466c7f32e8734f (diff) | |
| download | django-rest-framework-b6ca7248ebcf95a95e1911aa0b130f653b8bf690.tar.bz2 | |
required=False allows omission of value for output. Closes #2342
Diffstat (limited to 'rest_framework')
| -rw-r--r-- | rest_framework/fields.py | 2 | ||||
| -rw-r--r-- | rest_framework/serializers.py | 8 |
2 files changed, 9 insertions, 1 deletions
diff --git a/rest_framework/fields.py b/rest_framework/fields.py index aab80982..cc9410aa 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -288,6 +288,8 @@ class Field(object): try: return get_attribute(instance, self.source_attrs) except (KeyError, AttributeError) as exc: + if not self.required and self.default is empty: + raise SkipField() msg = ( 'Got {exc_type} when attempting to get a value for field ' '`{field}` on serializer `{serializer}`.\nThe serializer ' diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 6f89df0d..53f092d7 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -419,8 +419,14 @@ class Serializer(BaseSerializer): fields = [field for field in self.fields.values() if not field.write_only] for field in fields: - attribute = field.get_attribute(instance) + try: + attribute = field.get_attribute(instance) + except SkipField: + continue + if attribute is None: + # We skip `to_representation` for `None` values so that + # fields do not have to explicitly deal with that case. ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute) |
