Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/api-guide/serializers.md
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,22 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu

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.

It is also possible to create new serializer fields from any related model fields using the `extra_kwargs` option. For example:

class UserProfile(models.Model):
birthdate = models.DateField()
user = models.ForeignKey(User, on_delete=models.CASCADE)

class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['date_of_birth', 'first_name', 'last_name']
extra_kwargs = {
'date_of_birth': {'source': 'birthdate'},
'first_name': {'source': 'user.first_name'},
'last_name': {'source': 'user.last_name'}
Comment on lines +595 to +596

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new example uses dotted sources to pull fields from the related user. By default, ModelSerializer.create()/update() does not support writable dotted-source fields (it asserts unless you set read_only=True or implement explicit create/update handling). It’d help to either mark these example fields as read_only=True (via extra_kwargs) or add a short note clarifying the write behavior.

Suggested change
'first_name': {'source': 'user.first_name'},
'last_name': {'source': 'user.last_name'}
'first_name': {'source': 'user.first_name', 'read_only': True},
'last_name': {'source': 'user.last_name', 'read_only': True},

Copilot uses AI. Check for mistakes.
}

## Relational fields

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.
Expand Down
28 changes: 27 additions & 1 deletion rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1101,9 +1101,35 @@ def get_fields(self):
if source == '*':
source = field_name

# Get the right model and info for source with attributes
source_attrs = source.split('.')
source_info = info
source_model = model

attr_info = info
attr_model = model

for attr in source_attrs[:-1]:
if attr not in attr_info.relations:
break

attr_model = attr_info.relations[attr].related_model
Comment on lines +1113 to +1116

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dotted source traversal rewrites the field based on related model metadata, but it currently follows to-many relations too (e.g. M2M or reverse FK). That can generate a scalar field for sources like groups.name, which will then fail/behave incorrectly at runtime because attribute traversal hits a RelatedManager.

Consider bailing out when an intermediate relation has to_many=True (and keep source unchanged so build_field raises ImproperlyConfigured), or raise a clearer configuration error for dotted sources that traverse collections.

Suggested change
if attr not in attr_info.relations:
break
attr_model = attr_info.relations[attr].related_model
relation_info = attr_info.relations.get(attr)
if relation_info is None:
break
if getattr(relation_info, 'to_many', False):
# Do not rewrite sources that traverse to-many relations.
break
attr_model = relation_info.related_model

Copilot uses AI. Check for mistakes.
attr_info = model_meta.get_field_info(attr_model)
else:
attr = source_attrs[-1]
if (
attr in attr_info.fields_and_pk
or attr in attr_info.relations
or hasattr(attr_model, attr)
or attr == self.url_field_name
):
source = attr
source_info = attr_info
source_model = attr_model
Comment on lines +1105 to +1128

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic runs for every auto-generated field, even when source has no dotted path. You can avoid the extra split()/loop and repeated get_field_info() calls by guarding the new traversal with something like if '.' in source: (or if len(source_attrs) > 1: after splitting).

Suggested change
source_attrs = source.split('.')
source_info = info
source_model = model
attr_info = info
attr_model = model
for attr in source_attrs[:-1]:
if attr not in attr_info.relations:
break
attr_model = attr_info.relations[attr].related_model
attr_info = model_meta.get_field_info(attr_model)
else:
attr = source_attrs[-1]
if (
attr in attr_info.fields_and_pk
or attr in attr_info.relations
or hasattr(attr_model, attr)
or attr == self.url_field_name
):
source = attr
source_info = attr_info
source_model = attr_model
source_info = info
source_model = model
if '.' in source:
source_attrs = source.split('.')
attr_info = info
attr_model = model
for attr in source_attrs[:-1]:
if attr not in attr_info.relations:
break
attr_model = attr_info.relations[attr].related_model
attr_info = model_meta.get_field_info(attr_model)
else:
attr = source_attrs[-1]
if (
attr in attr_info.fields_and_pk
or attr in attr_info.relations
or hasattr(attr_model, attr)
or attr == self.url_field_name
):
source = attr
source_info = attr_info
source_model = attr_model

Copilot uses AI. Check for mistakes.

# Determine the serializer field class and keyword arguments.
field_class, field_kwargs = self.build_field(
source, info, model, depth
source, source_info, source_model, depth
)

# Include any kwargs defined in `Meta.extra_kwargs`
Expand Down
37 changes: 37 additions & 0 deletions tests/test_model_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import tempfile

import pytest
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
from django.core.serializers.json import DjangoJSONEncoder
from django.core.validators import (
Expand Down Expand Up @@ -726,6 +727,42 @@ class Meta:
""")
self.assertEqual(repr(TestSerializer()), expected)

def test_source_with_attributes(self):
class UserProfile(models.Model):
age = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)])
birthdate = models.DateField()
user = models.ForeignKey(User, on_delete=models.CASCADE)

class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('username', 'email', 'first_name', 'last_name', 'age', 'birthdate')
extra_kwargs = {
'username': {
'source': 'user.username',
},
'email': {
'source': 'user.email',
},
'first_name': {
'source': 'user.first_name',
},
'last_name': {
'source': 'user.last_name',
}
}

expected = dedent("""
UserProfileSerializer():
username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, source='user.username', validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>])
email = EmailField(allow_blank=True, label='Email address', max_length=254, required=False, source='user.email')
first_name = CharField(allow_blank=True, max_length=150, required=False, source='user.first_name')
last_name = CharField(allow_blank=True, max_length=150, required=False, source='user.last_name')
age = IntegerField(max_value=100, min_value=1)
birthdate = DateField()
""")
self.assertEqual(repr(UserProfileSerializer()), expected)


Comment on lines +765 to 766

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test covers the happy path for dotted sources, but it doesn’t cover an important failure mode introduced by the traversal: dotted sources that cross a to-many relation (M2M or reverse FK) should raise ImproperlyConfigured instead of generating a field that can’t be resolved at runtime. Adding an assertion test for a source like user.groups.name (or any to-many hop) would prevent regressions here.

Suggested change
def test_source_with_to_many_raises_improperly_configured(self):
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
class InvalidUserProfileSerializer(serializers.ModelSerializer):
groups = serializers.CharField(source='user.groups.name')
class Meta:
model = UserProfile
fields = ('groups',)
with self.assertRaises(ImproperlyConfigured):
InvalidUserProfileSerializer()

Copilot uses AI. Check for mistakes.
class DisplayValueTargetModel(models.Model):
name = models.CharField(max_length=100)
Expand Down
Loading