Search code examples
pythondjangodjango-modelsdjango-rest-frameworkdjango-serializer

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):
    """
    region
    """
    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": "st-01",
        "addressregion": 3
    },
    {
        "id": 14,
        "name": "tg-02",
        "addressregion": 4
    },
    {
        "id": 15,
        "name": "sx-01",
        "addressregion": 3
    }
]

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


Solution

  • You can do the following:

    class AvailableAreaSerializer(ModelSerializer):
    
        addressregion_name= serializers.ReadOnlyField(source='addressregion.name')
    
        class Meta:
            model = AvailableArea
            fields = ('id', 'name', 'addressregion_name')