gpt4 book ai didi

python - 外国字段如何显示名称而不是其 id?

转载 作者:太空狗 更新时间:2023-10-30 02:07:52 24 4
gpt4 key购买 nike

在我的 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):
"""
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 的name

最佳答案

您可以执行以下操作:

class AvailableAreaSerializer(ModelSerializer):

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

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

关于python - 外国字段如何显示名称而不是其 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47265385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com