简体   繁体   中英

How can the foreign field shows the name instead of its id?

In my models.py, there are two model, the AvailableArea has a foreign field refer to 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

In the serializers.py, I serialize all the fields:

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

In the views.py:

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

The rest framework data is like this:

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

I want the addressregion not shows the addressregion's id , but shows the addressregion's name .

You can do

class AvailableAreaSerializer(ModelSerializer):

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

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

just add the following code in your serializer:

addressregion_name = serializers.StringRelatedField()

#should be like the following

class AvailableAreaSerializer(ModelSerializer):

addressregion_name = serializers.StringRelatedField()

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

Your serializer should be like this:

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

and queryset in View should be:

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

select_related will fetch the result by joining both the table. For more info read this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM