10

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.

3 Answers 3

15

You can do the following:

class AvailableAreaSerializer(ModelSerializer): addressregion_name= serializers.ReadOnlyField(source='addressregion.name') class Meta: model = AvailableArea fields = ('id', 'name', 'addressregion_name') 
Sign up to request clarification or add additional context in comments.

Comments

6

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') 

1 Comment

The problem with this approach is that it is read_only. In other words, although it will bring the string representation to the endpoint you wont be able to update and create.
3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.