Skip to content

Serializer field with 'source' mapping to nullable foreign key field results in error while serializing #5750

Closed
@ozgurakcali

Description

@ozgurakcali

Steps to reproduce

Create a model with a nullable foreign key field

class MyModel(models.Model):
    foreign_field = models.ForeignKey(OtherModel, null=True)

class MyModelSerializer(serializers.ModelSerializer):
    foreign_field_attribute = serializers.CharField(source='foreign_field.my_attribute', allow_null=True, required=False)

Expected behavior

While retrieveing an entry with 'foreign_field' set to null, object should be serialized with 'foreign_field_attribute' set to None

Actual behavior

An exception is raised while trying to retrieve an instance with 'foreign_field' set to Null:
'NoneType' object has no attribute 'foreign_field'

The above works as expceted in version 3.6.2, but in version 3.7.3 (I do not know where in between the behavior is changed), raises an AttributeError. Seems like a change in fields.py / get_attribute method is causing this.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions