1

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, "previous": null, "results": [{"user": {"username": "smithb", "first_name": "Bob", "last_name": "Smith"}, "role_type": 2, "item": 1}, {"user": {"username": "jjones", "first_name": "Jane", "last_name": "Jones"}, "role_type": 2, "item": 1}]}

serializers.py

class RoleSerializer(serializers.ModelSerializer):

    user = PersonShortSerializer(many=False, read_only=True)

    class Meta:
        model = Role
        fields = 'user', 'role_type', 'item'

        def get_role_type(self, obj):
            return obj.name

models.py

class Role(models.Model):
    role_type = models.ForeignKey('RoleType')
    user = models.ForeignKey(Person)
    item = models.ForeignKey('Assets.Item')

class RoleType(models.Model):
    name = models.CharField(max_length=255)
    permissions = models.ManyToManyField(RolePermission,
                                         blank=True, null=True)

    def __unicode__(self):
        return self.name

1 Answer 1

0

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.

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

    class Meta:
        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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.