From a7072eb730813dbd93cbe33da220c067beddc6d1 Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Thu, 9 Jan 2014 23:19:25 +0100 Subject: [PATCH 1/2] Test case for #1129 --- rest_framework/tests/test_relations.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/rest_framework/tests/test_relations.py b/rest_framework/tests/test_relations.py index d19219c90..f52e0e1e5 100644 --- a/rest_framework/tests/test_relations.py +++ b/rest_framework/tests/test_relations.py @@ -98,3 +98,23 @@ class RelatedFieldSourceTests(TestCase): obj = ClassWithQuerysetMethod() value = field.field_to_native(obj, 'field_name') self.assertEqual(value, ['BlogPost object']) + + # Regression for #1129 + def test_exception_for_incorect_fk(self): + """ + Check that the exception message are correct if the source field + doesn't exist. + """ + from rest_framework.tests.models import ManyToManySource + class Meta: + model = ManyToManySource + attrs = { + 'name': serializers.SlugRelatedField( + slug_field='name', source='banzai'), + 'Meta': Meta, + } + + TestSerializer = type(str('TestSerializer'), + (serializers.ModelSerializer,), attrs) + with self.assertRaises(AttributeError): + TestSerializer(data={'name': 'foo'}) From f217f6870dec51b70ae5afcce8cb4bff54b511d9 Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Thu, 9 Jan 2014 23:32:50 +0100 Subject: [PATCH 2/2] Removed useless try/except --- rest_framework/relations.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 35c00bf1d..02185c2ff 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -65,16 +65,11 @@ class RelatedField(WritableField): def initialize(self, parent, field_name): super(RelatedField, self).initialize(parent, field_name) if self.queryset is None and not self.read_only: - try: - manager = getattr(self.parent.opts.model, self.source or field_name) - if hasattr(manager, 'related'): # Forward - self.queryset = manager.related.model._default_manager.all() - else: # Reverse - self.queryset = manager.field.rel.to._default_manager.all() - except Exception: - msg = ('Serializer related fields must include a `queryset`' + - ' argument or set `read_only=True') - raise Exception(msg) + manager = getattr(self.parent.opts.model, self.source or field_name) + if hasattr(manager, 'related'): # Forward + self.queryset = manager.related.model._default_manager.all() + else: # Reverse + self.queryset = manager.field.rel.to._default_manager.all() ### We need this stuff to make form choices work...