外部字段如何显示名称而不是id?

bxgwgixi  于 2022-10-22  发布在  Python
关注(0)|答案(3)|浏览(164)

在我的模型中。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

在序列化程序中。py,我序列化所有字段:

class AvailableAreaSerializer(ModelSerializer):
    """
    region
    """
    class Meta:
        model = AvailableArea
        fields = "__all__"

在views.py中:

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

其余框架数据如下:

[
    {
        "id": 13,
        "name": "st-01",
        "addressregion": 3
    },
    {
        "id": 14,
        "name": "tg-02",
        "addressregion": 4
    },
    {
        "id": 15,
        "name": "sx-01",
        "addressregion": 3
    }
]

我希望addressregion不显示addressregion的id,而是显示addressregion的m2n4o1p。

2vuwiymt

2vuwiymt1#

您可以执行以下操作:

class AvailableAreaSerializer(ModelSerializer):

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

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

epfja78i2#

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

addressregion_name = serializers.StringRelatedField()

应该如下所示

class AvailableAreaSerializer(ModelSerializer):

addressregion_name = serializers.StringRelatedField()

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

y1aodyip3#

序列化程序应该如下所示:

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

视图中的queryset应为:

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

select_related将通过连接这两个表来获取结果。欲了解更多信息,请阅读此

相关问题