-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Description
Checklist
- I have verified that that issue exists against the
master
branch of Django REST framework. - I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- This is not a usage question. (Those should be directed to the discussion group instead.)
- This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
- I have reduced the issue to the simplest possible case.
- I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)
Short Version
Can we please add the information in 3.0 Announcement about the use of to_representation
on serializers classes (cf. Removal of Transform Field) to the docs to help better explain how to change the representation of fields in ModelSerializers?
(Sorry about the non-standard format for the issue text, just made more sense this way given that it's a documentation suggestion (feature/functionality is great!)
I can do up a pull request which just moves the information in the 3.0 Announcement into serializers.md
(probably into override-serialization-and-deserialization-behaviour) if that suits?
Long Version
Outcome desired was to have a related field (i.e. ForeignKey
) on a ModelSerializer
that was writable by passing the pk
, but returned a nested representation. For example:
class ExampleModel(models.Model):
user = models.ForeignKey(User)
...
class ExampleUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["username", "email", ... ]
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = ExampleModel
fields = ["user",]`
Problem I struggled with was changing the representation to use the nested ExampleUserSerializer
, but to accept write input to TestSerializer
with just the User's pk
. For example, you could update the user
on ExampleModel
by sending a request with:
{"user": 3}
And get back the updated ExampleModel
as:
{"username": "myusername", "email": "me@world.com", ...}
Worked it out by adding a to_representation
method on the TestSerializer
(etc.) by referring to the bit about "Removal of Transform Field" in 3.0 Announcement. Found some information about this at override-serialization-and-deserialization-behaviour, but the example in the 3.0 Announcement just made it so much clearer.