I am looking for an easy way to subclass rest_framework.serializers.ModelSerializer from Django REST framework so that it serializes to a special dictionary for foreign key models fields with the name of the model class and the id value instead of just an integer / primary key. This should work for different models.
# models.py
class Author(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
book_written_by = models.ForeignKey(Author)
class Song(models.Model):
song_written_by = models.ForeignKey(Author)
# serializers.py
class CustomSerializer(serializers.ModelSerializer):
# What to do here? #
class BookSerializer(CustomSerializer):
class Meta:
model = Book
class SongSerializer(CustomSerializer):
class Meta:
model = Song
I would like to get the following result:
kleist = Author.objects.create(name='Kleist')
some_book = Book.objects.create(author=kleist)
BookSerializer(some_book).data == {'id': 1, 'book_written_by': {'Author': 1}} # Returns True
I tried to override get_related_field() and changed PrimaryKeyRelatedField to a CustomPrimaryKeyRelatedField and there I tried to override to_native() but I don't have access to the model field and its object itself but only to the pk value.