Control output of Django Rest Framework

2019-08-10 12:51发布

问题:

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:

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.