Skip to content

simple foreign key assignment with serializers #7414

@jerinpetergeorge

Description

@jerinpetergeorge

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.)

Suppose we have two models,

class Musician(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return f'{self.name}'


class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)

    def __str__(self):
        return f'{self.name} : {self.artist}'

and to create Album instance I have created a AlbumSerializer

class AlbumSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Album

and executed the code as

s = AlbumSerializer(data={'artist': 1, 'name': 'Foo'})
s.is_valid(True)
s.save()
print(s.data)
# {'id': 1, 'name': 'Foo', 'artist': 1}

This will return the PK of Musicians instance. But, many developers looking for an alternate solution which return a nested serializer response ( related SO post-DRF: Simple foreign key assignment with nested serializers? )

So, the common workaround to this problem is overriding the to_representation(...) method (of AlbumSerializer class). But, I there would be a DRF field which takes care of this situation.

Something like this will probably suite in the situation

from rest_framework import serializers


class PrimaryKeySerializerField(PrimaryKeyRelatedField):
    def __init__(self, serializer, **kwargs):
        self.serializer = serializer
        super().__init__(**kwargs)

    def use_pk_only_optimization(self):
        return False

    def to_representation(self, instance):
        return self.serializer(instance, context=self.context).data

Metadata

Metadata

Assignees

No one assigned

    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