我的REST API运行正常,但输出是所有ID号。如何让'role_type'显示名称而不是ID号?
输出:
{"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
答案 0 :(得分:0)
查看不同类型的序列化关系字段。
特别是RelatedField应该做你需要的,因为它将使用unicode值代表关系的目标。
class RoleSerializer(serializers.ModelSerializer):
user = PersonShortSerializer(many=False, read_only=True)
role_type = serializers.RelatedField()
class Meta:
model = Role
fields = ('user', 'role_type', 'item')
另请注意,RelatedField
是一个只读字段,因为在给定unicode表示的情况下无法确定适当的模型实例。如果您确实需要它可写,您可能希望查看实现custom relational field。