mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-29 13:04:03 +03:00
Merge pull request #335 from tomchristie/related-field-as-instance
Writable related fields should return a model instance from .from_native...
This commit is contained in:
commit
51a53b497b
|
@ -244,7 +244,7 @@ class RelatedField(WritableField):
|
||||||
return
|
return
|
||||||
|
|
||||||
value = data.get(field_name)
|
value = data.get(field_name)
|
||||||
into[(self.source or field_name) + '_id'] = self.from_native(value)
|
into[(self.source or field_name)] = self.from_native(value)
|
||||||
|
|
||||||
|
|
||||||
class ManyRelatedMixin(object):
|
class ManyRelatedMixin(object):
|
||||||
|
@ -288,6 +288,12 @@ class PrimaryKeyRelatedField(RelatedField):
|
||||||
def to_native(self, pk):
|
def to_native(self, pk):
|
||||||
return pk
|
return pk
|
||||||
|
|
||||||
|
def from_native(self, data):
|
||||||
|
try:
|
||||||
|
return self.queryset.get(pk=data)
|
||||||
|
except ObjectDoesNotExist:
|
||||||
|
raise ValidationError('Invalid hyperlink - object does not exist.')
|
||||||
|
|
||||||
def field_to_native(self, obj, field_name):
|
def field_to_native(self, obj, field_name):
|
||||||
try:
|
try:
|
||||||
# Prefer obj.serializable_value for performance reasons
|
# Prefer obj.serializable_value for performance reasons
|
||||||
|
@ -379,7 +385,7 @@ class HyperlinkedRelatedField(RelatedField):
|
||||||
|
|
||||||
# Try explicit primary key.
|
# Try explicit primary key.
|
||||||
if pk is not None:
|
if pk is not None:
|
||||||
return pk
|
queryset = self.queryset.filter(pk=pk)
|
||||||
# Next, try looking up by slug.
|
# Next, try looking up by slug.
|
||||||
elif slug is not None:
|
elif slug is not None:
|
||||||
slug_field = self.get_slug_field()
|
slug_field = self.get_slug_field()
|
||||||
|
@ -392,7 +398,7 @@ class HyperlinkedRelatedField(RelatedField):
|
||||||
obj = queryset.get()
|
obj = queryset.get()
|
||||||
except ObjectDoesNotExist:
|
except ObjectDoesNotExist:
|
||||||
raise ValidationError('Invalid hyperlink - object does not exist.')
|
raise ValidationError('Invalid hyperlink - object does not exist.')
|
||||||
return obj.pk
|
return obj
|
||||||
|
|
||||||
|
|
||||||
class ManyHyperlinkedRelatedField(ManyRelatedMixin, HyperlinkedRelatedField):
|
class ManyHyperlinkedRelatedField(ManyRelatedMixin, HyperlinkedRelatedField):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user