Skip to content Skip to sidebar Skip to footer

Control Output Of Django Rest Framework

My REST API is functioning correctly, but the output is all id numbers. How can I get 'role_type' to display the name instead of the ID number? Output: {'count': 2, 'next': null,

Solution 1:

Take a look at the different types of serializer relationship fields.

In particular RelatedField should do what you need as it'll represent the target of the relationship using its unicode value.

classRoleSerializer(serializers.ModelSerializer):
    user = PersonShortSerializer(many=False, read_only=True)
    role_type = serializers.RelatedField()

    classMeta:
        model = Role
        fields = ('user', 'role_type', 'item')

Also note that RelatedField is a read only field, as there's no way to determine the appropriate model instance given the unicode representation. If you did need it to be writable you might want to look at implementing a custom relational field.

Post a Comment for "Control Output Of Django Rest Framework"