Merge pull request #1343 from linovia/hotfix/1129

Fix for #1129
This commit is contained in:
Tom Christie 2014-01-13 01:32:09 -08:00
commit 2ecd984172
2 changed files with 25 additions and 10 deletions

View File

@ -65,16 +65,11 @@ class RelatedField(WritableField):
def initialize(self, parent, field_name): def initialize(self, parent, field_name):
super(RelatedField, self).initialize(parent, field_name) super(RelatedField, self).initialize(parent, field_name)
if self.queryset is None and not self.read_only: if self.queryset is None and not self.read_only:
try: manager = getattr(self.parent.opts.model, self.source or field_name)
manager = getattr(self.parent.opts.model, self.source or field_name) if hasattr(manager, 'related'): # Forward
if hasattr(manager, 'related'): # Forward self.queryset = manager.related.model._default_manager.all()
self.queryset = manager.related.model._default_manager.all() else: # Reverse
else: # Reverse self.queryset = manager.field.rel.to._default_manager.all()
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)
### We need this stuff to make form choices work... ### We need this stuff to make form choices work...

View File

@ -98,3 +98,23 @@ class RelatedFieldSourceTests(TestCase):
obj = ClassWithQuerysetMethod() obj = ClassWithQuerysetMethod()
value = field.field_to_native(obj, 'field_name') value = field.field_to_native(obj, 'field_name')
self.assertEqual(value, ['BlogPost object']) 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'})