|
10 | 10 | from django.utils.translation import gettext_lazy as _
|
11 | 11 |
|
12 | 12 | from rest_framework.fields import (
|
13 |
| - Field, empty, get_attribute, is_simple_callable, iter_options |
| 13 | + Field, SkipField, empty, get_attribute, is_simple_callable, iter_options |
14 | 14 | )
|
15 | 15 | from rest_framework.reverse import reverse
|
16 | 16 | from rest_framework.settings import api_settings
|
@@ -531,7 +531,30 @@ def get_attribute(self, instance):
|
531 | 531 | if hasattr(instance, 'pk') and instance.pk is None:
|
532 | 532 | return []
|
533 | 533 |
|
534 |
| - relationship = get_attribute(instance, self.source_attrs) |
| 534 | + try: |
| 535 | + relationship = get_attribute(instance, self.source_attrs) |
| 536 | + except (KeyError, AttributeError) as exc: |
| 537 | + if self.default is not empty: |
| 538 | + return self.get_default() |
| 539 | + if self.allow_null: |
| 540 | + return None |
| 541 | + if not self.required: |
| 542 | + raise SkipField() |
| 543 | + msg = ( |
| 544 | + 'Got {exc_type} when attempting to get a value for field ' |
| 545 | + '`{field}` on serializer `{serializer}`.\nThe serializer ' |
| 546 | + 'field might be named incorrectly and not match ' |
| 547 | + 'any attribute or key on the `{instance}` instance.\n' |
| 548 | + 'Original exception text was: {exc}.'.format( |
| 549 | + exc_type=type(exc).__name__, |
| 550 | + field=self.field_name, |
| 551 | + serializer=self.parent.__class__.__name__, |
| 552 | + instance=instance.__class__.__name__, |
| 553 | + exc=exc |
| 554 | + ) |
| 555 | + ) |
| 556 | + raise type(exc)(msg) |
| 557 | + |
535 | 558 | return relationship.all() if hasattr(relationship, 'all') else relationship
|
536 | 559 |
|
537 | 560 | def to_representation(self, iterable):
|
|
0 commit comments