Skip to content

Commit 2fc08b2

Browse files
committed
Add some documentation about source in extra_kwargs
1 parent a5b239e commit 2fc08b2

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

docs/api-guide/serializers.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,22 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu
580580

581581
Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the `extra_kwargs` option will be ignored.
582582

583+
It is also possible to create new serializer fields from any related model fields using the `extra_kwargs` option. For example:
584+
585+
class UserProfile(models.Model):
586+
birthdate = models.DateField()
587+
user = models.ForeignKey(User, on_delete=models.CASCADE)
588+
589+
class UserProfileSerializer(serializers.ModelSerializer):
590+
class Meta:
591+
model = UserProfile
592+
fields = ['date_of_birth', 'first_name', 'last_name']
593+
extra_kwargs = {
594+
'date_of_birth': {'source': 'birthdate'},
595+
'first_name': {'source': 'user.first_name'},
596+
'last_name': {'source': 'user.last_name'}
597+
}
598+
583599
## Relational fields
584600

585601
When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances.

0 commit comments

Comments
 (0)