我有以下型号:
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
答案是不使用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}
....
但是现在出现了一个新问题,与主键相关的序列化器有什么意义?