Checklist
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
Checklist
masterbranch of Django REST framework.Suppose we have two models,
and to create
Albuminstance I have created aAlbumSerializerand executed the code as
This will return the
PKofMusicians 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 (ofAlbumSerializerclass). But, I there would be a DRF field which takes care of this situation.Something like this will probably suite in the situation