What Is The Easiest Way To Get Custom Serialized Model With ForeignKey Field
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
Solution 1:
What you need is certainly achievable, but it is really breaking convention so personally I'd vote against doing so. Nevertheless, a way to achieve what you need is to use a SerializerMethodField
:
class BookSerializer(serializers.ModelSerializer):
book_written_by = serializers.SerializerMethodField('get_author')
class Meta:
model = User
def get_author(self, obj):
return {'Author': obj.book_written_by.pk}
This would return the exact output you wanted. If you decide to stick with the conventions, I'd prefer an output like this:
{'id': 1, 'book_written_by': {'id': 1, 'name': 'somebody'}}
The following serializer would return that for you:
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('id', 'name')
class BookSerializer(serializers.ModelSerializer):
book_written_by = AuthorSerializer()
Post a Comment for "What Is The Easiest Way To Get Custom Serialized Model With ForeignKey Field"