如何获取主键相关字段嵌套序列化器django rest框架的所有值

问题描述 投票:2回答:1

我有以下型号:

class SearchCity(models.Model):
    city = models.CharField(max_length=200)

class SearchNeighborhood(models.Model):
    city = models.ForeignKey(SearchCity, on_delete=models.CASCADE)
    neighborhood = models.CharField(max_length=200)

然后是以下嵌套的序列化器:

class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer):
    searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = SearchCity
        fields = ('city','searchneighborhood_set')
        read_only_fields =('city', 'searchneighborhood_set')

与视图配对:

class CityNeighborhoodView(ListAPIView):
    queryset = SearchCity.objects.all()
    serializer_class = CityNeighborhoodReadOnlySerializer

当我拨打api电话时,我得到了这个:

city: "Chicago"
    searchneighborhood_set: 
      0: 5 
      1: 4
      2: 3
city: "New York"
    searchneighborhood_set:
      0: 8
      1: 7
      2: 6

我只是获得相关对象的主键。哪个好我需要,但我也想要neighborhood这个名字怎么做到的?

编辑:

这个问题可能会有所启发。他们没有使用主键相关的序列化器,所以我的问题是(如果这当然有效,那么与主键相关的序列化器的重点是什么呢?

Django Rest Framework nested serializer not showing related data

json django serialization nested django-rest-framework
1个回答
2
投票

答案是不使用primarykeyrelatedserializer而是使用序列化器来序列化Searchneighborhood对象。

我改变了这个:

class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer):
    searchneighborhood_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = SearchCity
        fields = ('city','searchneighborhood_set')
        read_only_fields =('city', 'searchneighborhood_set')

对此:

class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer):
    searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True)

    class Meta:
        model = SearchCity
        fields = ('city','searchneighborhood_set')
        read_only_fields =('city', 'searchneighborhood_set')

并从这个输出:

city: "Chicago"
    searchneighborhood_set: 
      0: 5 
      1: 4
      2: 3
city: "New York"
    searchneighborhood_set:
      0: 8
      1: 7
      2: 6

到我想要的那个:

city: Chicago
    searchneighborhood_set:
         0: {pk: 5, neighborhood: 'River North}
    ....

但是现在出现了一个新问题,与主键相关的序列化器有什么意义?

© www.soinside.com 2019 - 2024. All rights reserved.