外国字段如何显示名称而不是其ID?

时间:2017-11-13 13:24:23

标签: python django django-rest-framework

在我的models.py中,有两个模型,AvailableArea有一个外地字段引用AddressRegion

class AddressRegion(models.Model):
    name = models.CharField(max_length=8)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name


class AvailableArea(models.Model):
    name = models.CharField(max_length=8)
    addressregion = models.ForeignKey(AddressRegion, default=1, related_name='availableareas', on_delete=models.CASCADE)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

在serializers.py中,我序列化了所有字段:

class AvailableAreaSerializer(ModelSerializer):
    """
    可用地区
    """
    class Meta:
        model = AvailableArea
        fields = "__all__"

在views.py中:

class AddressRegionListAPIView(ListAPIView):
    serializer_class = AddressRegionSerializer
    permission_classes = []
    queryset = AddressRegion.objects.all()

其余的框架数据是这样的:

[
    {
        "id": 13,
        "name": "福州一区",
        "addressregion": 3
    },
    {
        "id": 14,
        "name": "西南一区",
        "addressregion": 4
    },
    {
        "id": 15,
        "name": "西南一区",
        "addressregion": 3
    }
]

我希望addressregion不会显示地址区域id,但会显示地址区域name

3 个答案:

答案 0 :(得分:7)

你可以做到

class AvailableAreaSerializer(ModelSerializer):

    addressregion_name= serializers.ReadOnlyField(source='addressregion.name')

    class Meta:
        model = AvailableArea
        fields = ('id', 'name', 'addressregion_name')

答案 1 :(得分:3)

只需在序列化程序中添加以下代码:

addressregion_name = serializers.StringRelatedField()

#应该是这样的

class AvailableAreaSerializer(ModelSerializer):

addressregion_name = serializers.StringRelatedField()

class Meta:
    model = AvailableArea
    fields = ('id', 'name', 'addressregion__name')

答案 2 :(得分:2)

你的序列化器应该是这样的:

class AvailableAreaSerializer(ModelSerializer):
"""
可用地区
"""
class Meta:
    model = AvailableArea
    fields = ('id', 'name', 'addressregion__name')
视图中的

queryset应为:

queryset = AddressRegion.objects.all().select_related('addressregion')

select_related将通过加入表来获取结果。有关详情,请阅读this