mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-07 22:04:48 +03:00
Merge 45235e19cb
into b1035b2a87
This commit is contained in:
commit
ec3b19f593
|
@ -64,7 +64,7 @@ def is_simple_callable(obj):
|
|||
return len_args <= len_defaults
|
||||
|
||||
|
||||
def get_attribute(instance, attrs):
|
||||
def get_attribute(instance, attrs, required=True):
|
||||
"""
|
||||
Similar to Python's built in `getattr(instance, attr)`,
|
||||
but takes a list of nested attributes, instead of a single attribute.
|
||||
|
@ -82,6 +82,12 @@ def get_attribute(instance, attrs):
|
|||
instance = getattr(instance, attr)
|
||||
except ObjectDoesNotExist:
|
||||
return None
|
||||
# RelatedObjectDoesNotExist inherits from both ObjectDoesNotExist and
|
||||
# AttributeError, so ObjectDoesNotExist has to come first
|
||||
except (AttributeError, KeyError):
|
||||
if not required:
|
||||
raise SkipField
|
||||
raise
|
||||
if is_simple_callable(instance):
|
||||
try:
|
||||
instance = instance()
|
||||
|
|
|
@ -154,7 +154,7 @@ class RelatedField(Field):
|
|||
pass
|
||||
|
||||
# Standard case, return the object instance.
|
||||
return get_attribute(instance, self.source_attrs)
|
||||
return get_attribute(instance, self.source_attrs, self.required)
|
||||
|
||||
@property
|
||||
def choices(self):
|
||||
|
|
|
@ -340,6 +340,18 @@ class PKForeignKeyTests(TestCase):
|
|||
serializer = NullableForeignKeySourceSerializer()
|
||||
self.assertEqual(serializer.data['target'], None)
|
||||
|
||||
def test_foreign_key_not_required(self):
|
||||
"""
|
||||
Let's say we wanted to fill the non-nullable model field inside
|
||||
Model.save(), we would make it empty and not required.
|
||||
"""
|
||||
class ModelSerializer(ForeignKeySourceSerializer):
|
||||
class Meta(ForeignKeySourceSerializer.Meta):
|
||||
extra_kwargs = {'target': {'required': False}}
|
||||
serializer = ModelSerializer(data={'name': 'test'})
|
||||
serializer.is_valid(raise_exception=True)
|
||||
self.assertNotIn('target', serializer.data)
|
||||
|
||||
|
||||
class PKNullableForeignKeyTests(TestCase):
|
||||
def setUp(self):
|
||||
|
|
Loading…
Reference in New Issue
Block a user