Skip to content Skip to sidebar Skip to footer

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:

classBookSerializer(serializers.ModelSerializer):
    book_written_by = serializers.SerializerMethodField('get_author')

    classMeta:
        model = User

    defget_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:

classAuthorSerializer(serializers.ModelSerializer):
    classMeta:
        model = Authorfields= ('id', 'name')

classBookSerializer(serializers.ModelSerializer):
    book_written_by = AuthorSerializer()

Post a Comment for "What Is The Easiest Way To Get Custom Serialized Model With Foreignkey Field"